Python 在文件中搜索用户输入的关键字,然后打印包含关键字的每一行

Python 在文件中搜索用户输入的关键字,然后打印包含关键字的每一行,python,Python,在我的作业中,我收到了一个名为“more.txt”的文本文件,其中包含很多信息,但最重要的是,我专注于每一行的年份。我的任务是制作一个程序,读取“more.txt”,提示用户年份,并将该年份的每一行输出到另一个文本文件中 我无法理解的问题是,我的教授指定,如果用户输入的年份不完整,那么它必须工作。例如,年字段包含“1987”的行将由以下任何用户响应选择:{“1”、“19”、“198”、“1987”} 此外,如果用户输入“”“全部”或“全部”,则必须输出文本文件中的所有行 这是麻疹网站: 我目前的

在我的作业中,我收到了一个名为“more.txt”的文本文件,其中包含很多信息,但最重要的是,我专注于每一行的年份。我的任务是制作一个程序,读取“more.txt”,提示用户年份,并将该年份的每一行输出到另一个文本文件中

我无法理解的问题是,我的教授指定,如果用户输入的年份不完整,那么它必须工作。例如,年字段包含“1987”的行将由以下任何用户响应选择:{“1”、“19”、“198”、“1987”}

此外,如果用户输入“”“全部”或“全部”,则必须输出文本文件中的所有行

这是麻疹网站:

我目前的代码是:

input_file = open('measles.txt', 'r')
output_file_name = input("Please enter the name of the output file: ")
output_file = open(output_file_name, 'w')

for line in input_file:
    output_file.write(line)

output_file.close()
input_file.close()

像这样的东西可能有用。您可以检查一年是否以某个字符串开始(例如
'1'
'200'
),下面的代码应返回所有匹配行

编辑:

您似乎觉得这段代码太复杂了,但在复制/粘贴时出错,并破坏了解决方案。我修改了你的代码,使之更加简化和修复

input_file = open('measles.txt', 'r')
year = input("Please enter a year: ")
output_file_name = input("Please enter the name of the output file: ")
output_file = open(output_file_name, 'w')

for line in input_file:
    if year in ("", "all", "ALL") or line.split()[-1].startswith(year):
        output_file.write(line)

output_file.close()
input_file.close()

我找到了一个简单得多的答案。因为seare.txt中的年份号从一开始就是88个字符,所以我用它创建了一个if/elif语句

input_file = open('measles.txt', 'r')
year = input("Please enter a year: ")
output_file_name = input("Please enter the name of the output file: ")
output_file = open(output_file_name, 'w')

#   For loop that checks the end of the file for the year number
for line in input_file:
    if year == line[88:88+len(year)]:
        output_file.write(line)
    elif year == ("", "all", "ALL"):
        output_file.write(line)

output_file.close()
input_file.close()

在帖子中添加了一个链接。事实上,一个人可以从做别人的家庭作业中学到很多东西,这真是令人惊讶。