[英]Lists in Python (Using NLTK)
我正在嘗試以[[(the,cat),(cat,with),(with,fur)] [(the,dog),(dog,with),(with, ball)....... etc]來自一個文本文件,句子如下:
帶毛皮的貓\\帶球的狗\\ n
我一直在遇到的問題是,當我在文件中逐行讀取行時,制作元組(變量標簽)並創建最終列表(變量連接)時,會出現空的情況,連接變為0好吧,實際上不是0,但列表顯示為[[],[],[]]
這是該程序部分的代碼:open('corpus.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
我希望有人能理解我的問題,因為它讓我發瘋,而且我已經沒時間了。 我只是想知道我在這里做錯了什么,所以我可以在每個循環中更新我的連接列表,而不會丟失之前保存的內容。
謝謝你的幫助
您可以使用nltk.bigrams
來獲取元組,而無需擔心邊界條件恰到好處。 如果words
是一個句子中words
的列表,那么你就得到了所有的雙字母組合
bigrams = nltk.bigrams(words)
我沒有安裝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])])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.