我有一個文本文件,其中包含從a到z列出的千字。它看起來例如是這樣的:Python 3:從文本文件構建一個字典,然後在字典中搜索單詞
a
aaoo
aloor
azur
black
blue
church
croccoli
dark
den
...
zic
zip
我需要建立我的字典的鍵是小寫字母,並且其值設置包含 給定的字母詞的。例如:
myDict={'a':['aaoo','aloor','azur'], 'b':['black','blue'], 'c': ['church', 'croccoli'],'d':['dark','den'], and so on}
然後我需要提示用戶輸入一個字和打印包含單詞的所有字符的文件中的所有字。
wordFind=("Enter word: ")
wordFind=wordFind.lower()
wordFind=set(wordFind) #I convert to set to use intersection
例如,我在wordFind鍵入單詞「ABC」,然後「A」,「B」,「C」將與myDict的「鑰匙」相交,結果打印出將包括所有myDict的關鍵字'a','b','c'中的值。
編輯:所謂 「交叉點」 在這裏我的意思是2套(wordFind和myDict)之間的交叉點 - 希望這足夠清楚..
到目前爲止我的代碼是:
n=open("a7.txt","r")
line=n.readlines()
myDict={}
def myDict():
for word in line:
word=word.strip().lower()
if word in myDict:
myDict[word[0]].append(word)
else:
myDict[word[0]]=word
wordFind=("Enter word: ")
wordFind=wordFind.lower()
wordFind=set(wordFind)
# I get stuck at this second part, which requires me to use intersection
temp={}
for word in wordFind:
temp= word.intersection(myDict)
print(temp)
n.close()
但我得到這個錯誤:
Traceback (most recent call last):
File "/Users/annie_mabu/Documents/CS/bt2.py", line 21, in <module>
temp= word.intersection(myDict)
AttributeError: 'str' object has no attribute 'intersection'
任何人都可以告訴我我哪裏犯了錯誤,以及如何解決它?
我不明白你所說的「交集」的意思是什麼,不喜歡猜測。請擴展你的解釋(編輯你的問題,而不是在這裏的意見)。 – martineau 2015-04-04 20:05:18
「wordFind」或「myDict」都沒有設置,因此「十字路口」令人困惑。你的意思是會員嗎? – dawg 2015-04-05 00:59:27