我刚接触python,并为自己找到了一个个人项目。我试图解析一个大的文本文件以查找单词出现的地方,但是我似乎无法使代码正常工作。它是这样开始的:
file = 'randomfile.txt'
with open(file) as f:
word = input("Enter a word: ")
line = f.readline()
num_line = 1
while line:
if word in line:
print("line {}: {}".format(num_line, line.strip()))
print("Here are ___ I found with the word" + word)
num_line += 1
f.close()
此代码将运行,但不会提供搜索词的输出,我无法看到为什么不这样做,除非python未读取路径中的文本文件,或者未读取第四行代码好吗我该如何解决这个问题?
答案 0 :(得分:0)
这将起作用:
with open(randonfile.txt",'r') as f:
word = input("Enter a word: ")
line = f.readline()
num_line = 1
for words in line.split():
if word in words:
print("line {}: {}".format(num_line, line.strip()))
print("Here are ___ I found with the word" + word)
num_line += 1
答案 1 :(得分:0)
您的代码存在的问题是,仅读取第一行,而从不遍历整个文件。
with open(file) as f:
word = input("Enter a word: ")
line = f.readline() # this is the only place you read a line
num_line = 1
while line:
if word in line:
print("line {}: {}".format(num_line, line.strip()))
print("Here are ___ I found with the word" + word)
num_line += 1
您应该阅读while
循环中的下一行,如下所示:
with open(file) as f:
word = input("Enter a word: ")
line = f.readline()
num_line = 1
while line:
if word in line:
print("line {}: {}".format(num_line, line.strip()))
line = f.readline() # <-- read the next line
print("Here are ___ I found with the word" + word)
num_line += 1
现在您正在阅读文件。下一个问题是,仅在while循环结束后才递增行号num_line += 1
,您需要将其移至循环内,以便跟踪已处理的行数。
with open(file) as f:
word = input("Enter a word: ")
line = f.readline()
num_line = 1
while line:
if word in line:
print("line {}: {}".format(num_line, line.strip()))
line = f.readline() # <-- read the next line
num_line +=1 # <-- increase the counter in the loop
print("Here are ___ I found with the word" + word)
您不需要f.close()
,with_statement
会自动关闭文件。您也可以直接在文件指针f
上循环,以读取每一行,如下所示:
file = 'randomfile.txt'
with open(file) as f:
word = input("Enter a word: ")
num_line = 1
for line in f: # step through each line of the file
if word in line:
print("line {}: {}".format(num_line, line.strip()))
num_line +=1 # <-- increase the counter in the loop
print("Here are ___ I found with the word" + word)
# f.close() -- not needed
我将把它留给您修复打印声明。
答案 2 :(得分:0)
您可以执行以下操作:
word = input("Enter a word: ")
with open(file) as f:
for idx, line in enumerate(f):
# we need to use lower() and split() because we don't want to count if word = 'aaa' and line 'AAAaaa' returns True
if word.lower() in line.lower().split():
print("line {}: {}".format(idx, line.strip()))