我有一个文本文件,从a到z列出了上千个单词。它看起来像这样:
a
aaoo
aloor
azur
black
blue
church
croccoli
dark
den
...
zic
zip
我需要建立我的字典,它的键是小写字母,其值是包含 给你的信。例如:
^{pr2}$然后我需要提示用户输入一个单词,并打印包含该单词所有字符的文件中的所有单词。在
wordFind=("Enter word: ")
wordFind=wordFind.lower()
wordFind=set(wordFind) #I convert to set to use intersection
例如,我输入一个单词“abc”,那么wordFind中的'a'、'b'、'c'将与myDict中的'key'相交,输出的结果将包括myDict中键'a'、'b'、'c'中的所有值。在
编辑:这里的“交集”是指两个集合之间的交集(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'
有人能告诉我我在哪里犯了错误,以及如何改正它吗?在
我需要把这个文本文件转换成字典,比如:myDict={'a':'所有单词都以a开头','b':所有单词都以b开头,等等}
我从这个函数开始:
然后我使用wordFind=(“enterword:”),当我输入一个与myDict中的键值相交的wordFind时,结果将给出该交集中的所有值。
如果您只需要一个与输入的单词以相同字母开头的单词列表,则类似于:
^{pr2}$应该行得通。在
如果您想要更广泛的匹配,例如匹配的单词需要以您输入的同一组字符开头,则如下所示:
应该行得通。在
编辑:每个评论:
对于输入“abc”,如果您想要一个以“a”、“b”或“c”开头的单词的列表,则可以使用以下类似的方法:
如果您想单独使用它们,而不是在一个列表中,可以执行以下操作:
只需阅读一个列表,其中包含每个首字母的键:
那么你就有了这样一句话:
^{pr2}$然后您可以编写一个简单的函数来查找您的单词:
或者,如果您知道您的文件中有所有26个字母,您可以将所有26个字母的开头设置为空列表:
通过“.intersection”,您可能会想到sets:
但是,无论您是否有list、dict、set、string,
in
关键字是测试单个元素成员资格的最佳方法:您可能需要扩展您所说的“交叉点”,但请尝试以下操作:
相关问题 更多 >
编程相关推荐