Python中的列表(使用NLTK)

2024-04-26 03:59:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个文本文件中以[[(the,cat),(cat,with),(with,fur)][(the,dog),(dog,with),(with,ball)………等形式列出一个列表,其中的句子如下:

the cat with fur \n the dog with ball \n

我遇到的问题是,当我逐字读取文件中的行,创建元组(变量标签)和创建最终列表(变量连接)时,如果连接到0,就会出现空白。实际上不是0,但列表显示为[[],[],[]

这是该部分程序的代码: 打开('语料库.txt','r')作为f:

with open('corpus.txt', 'r') as f:
    for line in f:
        cnt = 0
        sa = nltk.word_tokenize(line)
        label[:] = []

        for i in sa:
            words.append(i)
            if cnt>0:
                try: label +=[(prev , i)]
                except: NameError
            prev = i 
            cnt = cnt + 1

        if label != []:
            connection += [label]
            print connection

我希望有人能理解我的问题,因为它快把我逼疯了,我的时间不多了。我只想知道我在这里做错了什么,这样我就可以在每个循环中更新我的连接列表,而不会丢失之前保存的内容。在

谢谢你的帮助


Tags: theintxt列表forifwithline
2条回答

我没有安装NLTK,但是看看这个是否适合您:

with open('corpus.txt', 'r') as f:
    answer = []
    for line in f:
        cnt = 0
        sa = nltk.word_tokenize(line)
        answer.append([tuple([char, sa[i+1]]) for i,char in enumerate(sa[:-1])])

您可以使用nltk.bigrams获得元组,而不必担心边界条件是否正确。如果words是一个句子中单词的列表,则可以得到

bigrams = nltk.bigrams(words)

相关问题 更多 >