Python 如何读取文件并将每行转换为字符串,然后查看用户输入中是否有任何字符串?

Python 如何读取文件并将每行转换为字符串,然后查看用户输入中是否有任何字符串?,python,string,file,Python,String,File,在我的程序中,我试图做的是让程序打开一个包含许多不同单词的文件 接收用户输入并检查文件中的任何单词是否在用户输入中 在文件中redflags.txt: happy angry ball jump 每个单词在不同的行上 例如,如果用户输入是“嘿,我是一个球”,那么它将打印redflag。 如果用户输入是“嘿,这是一个球体”,那么它将打印noflag Redflags = open("redflags.txt") data = Redflags.read() text_post = raw_

在我的程序中,我试图做的是让程序打开一个包含许多不同单词的文件

接收用户输入并检查文件中的任何单词是否在用户输入中

在文件中redflags.txt

happy
angry 
ball 
jump
每个单词在不同的行上

例如,如果用户输入是“嘿,我是一个球”,那么它将打印redflag。 如果用户输入是“嘿,这是一个球体”,那么它将打印noflag

Redflags = open("redflags.txt")

data = Redflags.read()
text_post = raw_input("Enter text you wish to analyse")
words = text_post.split() and text_post.lower()

if data in words:
  print("redflag")
else:
 print("noflag")      

这应该能奏效!集合通常比查找列表比较快得多。集合可以告诉您在这种情况下的交集(重叠单词)、差异等。我们使用包含单词列表的文件,删除换行符、小写字母,然后得到第一个列表。第二个列表是根据用户输入创建的,并按间距拆分。现在我们可以执行集合交集,查看是否存在任何常用词

# read in the words and create list of words with each word on newline
# replace newline chars and lowercase
words = [word.replace('\n', '').lower() for word in open('filepath_to_word_list.txt', 'r').readlines()]
# collect user input and lowercase and split into list
user_input = raw_input('Please enter your words').lower().split()

# use set intersection to find if common words exist and print redflag
if set(words).intersection(set(user_input)):
    print('redflag')
else:
    print('noflag')

我建议您使用列表理解

看看这段代码,它满足您的需求(我将在下面解释):

产出1:

Enter text you wish to analyse:i am sad
NoFlag
产出2:

Enter text you wish to analyse:i am angry
RedFlag
因此,首先打开文件并使用
readlines()
读取它们,这将给出文件中的行列表

>>> data = Redflags.readlines()
['happy\n', 'angry \n', 'ball \n', 'jump\n']
查看所有不需要的空格、换行符(\n)使用
strip()
删除它们!但是您不能
strip()
a列表。因此,从列表中选取单个项目,然后应用
strip()
。这可以通过使用列表理解有效地完成

data = [d.strip() for d in data]
另外为什么在Python3中使用
raw\u input()
而使用
input()

获取并拆分
输入后
文本

fin_list = [i for i in data if i in text_post]
我正在创建一个项目列表,其中来自
数据的
I
(每个项目)也是
文本列表中的。这样我就得到了两个列表中的公共项

>>> fin_list
['angry']           #if my input is "i am angry"
注意:在python中,空列表被视为
false

>>> bool([])
False
有值的被认为是真的

>>> bool(['some','values'])
True

这样,仅当列表非空时才会执行if含义“红旗”仅在两个列表之间找到某个常用项时才会打印。你得到了你想要的。

对于初学者来说,这个:
words=text\u post.split()和text\u post.lower()
没有做你认为它在做的事情。您需要
words=text\u post.lower().split()
。不使用
set
,您也可以使用列表生成器,但是set很好,特别是在以后不需要任何重复值的情况下。我认为从文件中获取单词可能是更好的方法。见下面我的答案。
>>> bool([])
False
>>> bool(['some','values'])
True