【问题标题】:searching a text file for an inputted word in python在 python 中搜索文本文件以查找输入的单词
【发布时间】:2013-05-27 05:33:02
【问题描述】:

所以基本上我在一个文本文件中有一个很大的单词列表,当用户输入一个单词来检查拼写时,我希望能够搜索匹配的单词,这就是我到目前为止所拥有的。

f = open('words.txt', 'r')
wordCheck = input("please enter the word you would like to check the spelling of: ")

for line in f:
    if 'wordCheck' == line:
        print ('That is the correct spelling for '+wordCheck)
    else:
        print ( wordCheck+ " is not in our dictionary")
    break

当我输入一个单词时,我会立即得到 else 语句,我认为它甚至不会读取文本文件。 我应该改用while循环吗?

while wordCheck != line in f

我是 python 新手,最终我希望用户能够输入一个单词,如果拼写不正确,程序应该打印出一个匹配单词列表(75% 的字母或更多匹配)。

任何帮助将不胜感激

【问题讨论】:

  • 为什么你的代码中有break

标签: python list text for-loop while-loop


【解决方案1】:

你可以这样做:

wordCheck = raw_input("please enter the word you would like to check the spelling of: ")
with open("words.txt", "r") as f:
    found = False    
    for line in f:
        if line.strip() == wordCheck:
            print ('That is the correct spelling for '+ wordCheck)
            found = True
            break
    if not found:
        print ( wordCheck+ " is not in our dictionary")

这需要一个输入,打开文件然后逐行检查输入单词是否与字典中的行匹配,如果它打印消息,否则如果它没有剩余行打印输入单词不在字典中。

【讨论】:

  • while line.readline() 似乎有点复杂......为什么不只是 for line in f
  • 另外,从行中删除 \n 更有意义,而不是将其添加到字符串中...if line.strip() == wordCheckstr(wordCheck) 是多余的,因为 raw_input 始终是一个字符串
  • 最后,如果没有找到,那么found 将不存在(在循环之前将其设置为False),所以你会在那一行得到一个NameError...并且,一旦找到,您应该 break 停止浏览该文件
【解决方案2】:

因为您只在第一行中断之前循环了它。

wordCheck = input("please enter the word you would like to check the spelling of: ")
with open('words.txt', 'r') as f:
    for line in f:
        if wordCheck in line.split():
            print('That is the correct spelling for '+wordCheck)
            break
    else:
        print(wordCheck + " is not in our dictionary")

此处使用了for/else,因此如果在任何行中都找不到该单词,则将运行else: 块。

【讨论】:

  • 解决了不搜索位,但现在它为文件的每一行(10000+ 字)打印 else 语句,我只想让它运行,当它找到打印结果的东西时
  • @JohnConneely 它不应该为每一行打印else,但只有在没有调用break的情况下才在循环之后
  • 您复制/粘贴的示例代码仍然有同样的错误。 'wordcheck' == line: 没有使用输入命令中分配的wordCheck 变量
  • 糟糕,应该是 in 而不是 ==
  • 那行得通!谢谢,我想我也会使用@muski 的回答来继续前进!
【解决方案3】:

它不会按照正确的拼写算法进行拼写,但您可以找到相似的字词:

from difflib import get_close_matches

with open('/usr/share/dict/words') as fin:
    words = set(line.strip().lower() for line in fin)

testword = 'hlelo'
matches = get_close_matches(testword, words, n=5)
if testword == matches[0]:
    print 'okay'
else:
    print 'Not sure about:', testword
    print 'options:', ', '.join(matches)

#Not sure about: hlelo
#options: helot, hello, leo, hollow, hillel

您可以调整“截止”和其他参数 - 检查get_close_matches 的文档difflib module

您可能想做的是看一下:https://pypi.python.org/pypi/aspell-python/1.13,它是 aspell 库的 Python 包装器,它会提供更好的建议,并且还会扩展到多个字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2017-08-28
    相关资源
    最近更新 更多