如果在我创建的文本文件中找不到用户输入的输入,我将尝试打印“无”。如果在文本文件中找到单词 的行,它也应该打印。
我现在的问题是它没有同时执行两个条件。如果要删除“ user_pass中没有行”,它将不会打印任何内容。我只希望用户能够知道用户输入的字符串是否可以在文件中找到,并且将打印该行;如果找不到,则将打印“无”。
我注释掉了我尝试修复代码的地方,但是没有用。
我的下面的代码:
def text_search(text):
try:
filename = "words.txt"
with open(filename) as search:
print('\nWord(s) found in file: ')
for line in search:
line = line.rstrip()
if 4 > len(line):
continue
if line.lower() in text.lower():
print("\n" + line)
# elif line not in text: # the function above will not work if this conditional commented out
# print("None")
# break
# if line not in text: # None will be printed so many times and line.lower in text.lower() conditional will not work
# print("none")
except OSError:
print("ERROR: Cannot open file.")
text_search("information")
答案 0 :(得分:1)
我认为您需要将for line in search:
更改为for line in search.readlines():
,我认为您从未从文件中读取过...您是否尝试过仅print(line)
并确保您的程序都在读书吗?
@EDIT
这是我要解决的问题的方式:
def text_search(text):
word_found = False
filename = "words.txt"
try:
with open(filename) as file:
file_by_line = file.readlines() # returns a list
except OSError:
print("ERROR: Cannot open file.")
print(file_by_line) # lets you know you read the data correctly
for line in file_by_line:
line = line.rstrip()
if 4 > len(line):
continue
if line.lower() in text.lower():
word_found = True
print("\n" + line)
if word_found is False:
print("Could not find that word in the file")
text_search("information")
我喜欢这种方法,因为
try:
子句中(我不想隐藏我的错误,但这并不是什么大问题,因为您在指定OSError
方面做得很好,但是如果{{1 }}发生在OSError
期间,由于某种原因……您永远不会知道!)
如果这有帮助,请您点击绿色的勾号:)答案 1 :(得分:0)
尝试一下:-
def find_words_in_line(words,line):
for word in words:
if(word in line):
return True;
return False;
def text_search(text,case_insensitive=True):
words = list(map(lambda x:x.strip(),text.split()));
if(case_insensitive):
text = text.lower();
try:
filename = 'words.txt'
with open(filename) as search:
found = False;
for line in search:
line = line.strip();
if(find_words_in_line(words,line)):
print(line);
found = True;
if(not found):
print(None);
except:
print('File not found');
text_search('information');
不是很了解您的代码,因此可以根据您的要求自行编写代码。