python3:从文本文件构建dict,然后在di中搜索单词

2024-09-29 23:16:39 发布

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

我有一个文本文件,从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'

有人能告诉我我在哪里犯了错误,以及如何改正它吗?在


Tags: toinforuse错误line单词lower
3条回答

我需要把这个文本文件转换成字典,比如:myDict={'a':'所有单词都以a开头','b':所有单词都以b开头,等等}

我从这个函数开始:

def make_dict():
    d = {}
    with open("a7.txt","r") as wordfile:
        for word in wordfile:
            word = word.strip().lower()
            first = word[0]
            if first not in d: d[first] = []
            d[first].append(word)
    return d

myDict = make_dict()

然后我使用wordFind=(“enterword:”),当我输入一个与myDict中的键值相交的wordFind时,结果将给出该交集中的所有值。

如果您只需要一个与输入的单词以相同字母开头的单词列表,则类似于:

^{pr2}$

应该行得通。在

如果您想要更广泛的匹配,例如匹配的单词需要以您输入的同一组字符开头,则如下所示:

wordFind = raw_input("Enter word: ")   # raw_input for Python2, input for Python3
wordFind = wordFind.lower()
find_first = wordFind[0]
matches = [w for w myDict[find_first] if w.startswith(wordFind)]  # This is different
print(matches)

应该行得通。在

编辑:每个评论:

对于输入“abc”,如果您想要一个以“a”、“b”或“c”开头的单词的列表,则可以使用以下类似的方法:

wordFind = raw_input("Enter word: ")   # raw_input for Python2, input for Python3
wordFind = wordFind.lower()
matches = []
for c in wordFind: matches.extend(myDict[c])
print(matches)

如果您想单独使用它们,而不是在一个列表中,可以执行以下操作:

wordFind = raw_input("Enter word: ")   # raw_input for Python2, input for Python3
wordFind = wordFind.lower()
matches = {}
for c in wordFind: matches[c] = myDict[c]
print(matches)

只需阅读一个列表,其中包含每个首字母的键:

with open(ur_file) as f:
    d={}
    for word in f:
        d.setdefault(word[0].lower(), []).append(word)

那么你就有了这样一句话:

^{pr2}$

然后您可以编写一个简单的函数来查找您的单词:

>>> def f(s): return s in d[s[0]]
... 
>>> f('art')
False
>>> f('aaoo')
True

或者,如果您知道您的文件中有所有26个字母,您可以将所有26个字母的开头设置为空列表:

d={k:list() for k in 'abcdefghijklmnopqrstuvwxyz'}
with open(ur_file) as f:
    for word in f:
        d[word[0].lower()].append(word)

通过“.intersection”,您可能会想到sets

>>> set(['a', 'aaoo', 'aloor', 'azur']).intersection(set(['art']))
set([])
>>> set(['a', 'aaoo', 'aloor', 'azur']).intersection(set(['aaoo']))
set(['aaoo'])

但是,无论您是否有list、dict、set、string,in关键字是测试单个元素成员资格的最佳方法:

>>> 'art' in set(['a', 'aaoo', 'aloor', 'azur'])
False
>>> 'azur' in set(['a', 'aaoo', 'aloor', 'azur'])
True

您可能需要扩展您所说的“交叉点”,但请尝试以下操作:

words = [w.strip().lower() for w in open("a7.txt").read().splitlines()]

word_dict = {}
for word in words:
    if word[0] in word_dict:
        word_dict[word[0]].append(word)
    else:
        word_dict[word[0]] = [word]

wordFind = raw_input("Enter word: ").strip().lower()
print '\n'.join(word_dict[wordFind[0]])

相关问题 更多 >

    热门问题