Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python检查txt文件中是否有某个单词_Python_Python 2.7 - Fatal编程技术网

使用python检查txt文件中是否有某个单词

使用python检查txt文件中是否有某个单词,python,python-2.7,Python,Python 2.7,我根据用户输入制作了一个程序,并在程序中使用txt文件来检查用户输入是否等于txt文件 my_age = open('c:\\file\\user_ask_about_my_age') my_age_read = my_age.read() user = raw_input("ask") if user in my_Age_read: print "I am 10 years old " txt文件: what is your age how ol

我根据用户输入制作了一个程序,并在程序中使用txt文件来检查用户输入是否等于txt文件

my_age = open('c:\\file\\user_ask_about_my_age')
my_age_read = my_age.read()
user = raw_input("ask")
if user in my_Age_read:
   print "I am 10 years old "
txt文件:

what is your age
how old are you
问题是,如果用户键入我的txt中存在的任何字符(询问…),程序将打印
我10岁了

如何让我的程序像字符串一样读取每行的txt文件?


我需要一个简单的方法和一个小代码来解决我的问题,因为我有很多文本文件。

请确保其他文件位于同一目录中,然后在脚本顶部添加:

import myfile
如果此文件包含打印要打印的内容的函数,则可以使用调用此函数

myfile.print_function()

我认为你可以通过这种方式实现你的要求:

with open('c:\\file\\user_ask_about_my_age', 'r') as fd:
    lines = fd.readlines()
lines = [line.strip('\n') for line in lines]
user = raw_input("ask")
for line in lines:
    if user == line:
        print "i am 10 years old "

my_file.py
的内容添加到函数中(可以在任何文件中),并从程序中调用该函数?谢谢,但我有很多文本文件,我不能为每个文件都这样做。有简单的方法吗??