【问题标题】:why is my code returning 0 even though word exists in file即使文件中存在单词,为什么我的代码仍返回 0
【发布时间】:2021-12-09 13:47:58
【问题描述】:

所以这是我尝试查找用户输入的单词并查找包含该单词的行数,如果没有行包含该单词,则输出未找到但是当我输入一个我知道文件中存在的单词时它返回 0 并且不仅文件中的单词它甚至没有像我想要的那样输出没有找到。 (这是我的代码)

response = input('Please enter words: ')
letters = response.split()

count = 0

with open("alice.txt", "r", encoding="utf-8") as program:
    for line in program:
        if letters in line:
            count += 1
            if(count < 1):
                print("not found")
print(count)

【问题讨论】:

  • "split" 返回一个列表,但 "line" 是一个字符串。列表永远不在字符串中。您需要一个内部循环来逐个检查“字母”中的每个单词。
  • str.split() 返回按空格字符拆分的字符串列表。为什么输入提示说“输入单词”,但你在拆分后将它分配给一个名为letters的变量?
  • 请注意,由于它当前是缩进的,if count &lt; 1 块是无法访问的代码,因为该条件永远不会为真。

标签: python string null


【解决方案1】:

你正在做的事情是行不通的,拆分函数返回一个字符串列表,你正在检查该列表与单个字符串。

这是你想做的吗?

response = input("Please enter a word: ")
count = 0

with open("alice.txt", 'r') as program:
    for line in program:
        if response in line:
            count += 1
    if count == 0:
        print("not found")

print(count)

【讨论】:

  • 感谢您的帮助,但是当我尝试使用它时,它确实说找不到,但是我使用的单词在文件中
【解决方案2】:

您在将 txt 文件作为单行而不是作为单行列表打开时遇到问题。

添加“.readlines()”可以解决这个问题!

我还继续将各个行设置为“行”,然后在新的“行”变量中搜索输入词。

response = input('Please enter words: ')
letters = response.split()


count = 0
foo = open(
     "alice.txt", "r",
     encoding="utf-8").readlines()


for line in foo:
    for word in letters:
        if word in line:
            count += 1


if(count < 1):
    print("not found")
else:
    print(count)

【讨论】:

  • 感谢您的回复和帮助,但是当我尝试使用它时,它确实说找不到,但是我使用的单词在文件中
【解决方案3】:

您的代码中不需要拆分功能和 if 条件错误的位置。请参考以下代码。

response = input('Please enter word: ')
count = 0

with open("alice.txt", "r", encoding="utf-8") as program:
    for line in program:
        if response in line:
            count += 1

if count == 0:        
    print('Not found')
else:
    print(count)

【讨论】:

  • 您好,谢谢您的帮助,但是当我尝试使用它时,它确实说找不到,但是我使用的单词在文件中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 2018-04-28
  • 1970-01-01
  • 2021-02-12
相关资源
最近更新 更多