【问题标题】:Python - Count search words in a text file -- Problem with print(dummy.read())Python - 计算文本文件中的搜索词 - 打印问题(dummy.read())
【发布时间】:2022-09-25 20:36:36
【问题描述】:

我对编码这个话题很陌生,所以我希望我的问题不是太愚蠢。

目前我真的在开始并尝试解决一些小练习来使用语法。 我今天的目标是一个在文本文件中搜索搜索词的小程序。

该程序应该变得更大,因此我尝试在功能上尽可能地du。 所以我有一个函数来处理虚拟文本(将有第二个函数应该处理手动输入)和一个函数,它只是用于计算文本中的单词。

我的问题围绕我注释掉的第 3 行展开。我有打开文本文件的功能,然后我想在我要求搜索词之前在控制台中打印文本。如果我不打印它,程序运行正常。当我在第 3 行注释并打印文本时,命中的结果始终为 0。

也许您可以帮助我理解为什么会发生这种情况,我必须学习什么以及如何解决它。

def dummytext():
    with open(\"dummy.txt\",\"r\",encoding=\"utf8\") as dummy_text:
#       print(dummy_text.read())
        search_word=input(\"Which word to search for: \")
        return count_words(dummy_text.read(), search_word)

def count_words(search_text, search_word):
    search_count =search_text.count(search_word)
    return search_word, search_count



result = dummytext()
print(\"The word \" + str(result[0])+ \" appears \"+str(result[1])+\" times in the dummy text\")
  • 对文件调用一次.read()后,当前文件位置在最后;再次调用.read() 将不会返回任何内容(除非已将更多数据添加到文件中)。如果您想多次阅读整个文件,则需要关闭并重新打开它,或者在文件上调用.seek(0) 以倒回开头。

标签: python


【解决方案1】:

你其实很亲近……

您需要设置一个变量来获取读取的内容。然后从那里进行搜索。

所以,这有效:

def dummytext():
    with open("F:/code/some_text.txt","r",encoding="utf8") as dummy_text:
        x = dummy_text.read()
        print(x)

        search_word=input("Which word to search for: ")
        return count_words(x, search_word)

def count_words(search_text, search_word):
    search_count =search_text.count(search_word)
    return search_word, search_count



result = dummytext()
print("The word " + str(result[0])+ " appears "+str(result[1])+" times in the dummy text")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2014-11-04
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    相关资源
    最近更新 更多