如何在python中获得与文件中的word完全匹配的word
我想从totaleducation文件中匹配的字符串中提取单词。若返回正确,若它是在一个单词中,如BCA,但当我提取计算机应用程序的MCA主控程序时,它忽略这一行如何在python中获得与文件中的word完全匹配的word,python,Python,我想从totaleducation文件中匹配的字符串中提取单词。若返回正确,若它是在一个单词中,如BCA,但当我提取计算机应用程序的MCA主控程序时,它忽略这一行 infile = open('file.txt', 'r') string = infile.read() def extract_edu(string): with open('totaleducation.txt', 'r') as totaledu: edu_set=[] for edu
infile = open('file.txt', 'r')
string = infile.read()
def extract_edu(string):
with open('totaleducation.txt', 'r') as totaledu:
edu_set=[]
for edu in totaledu:
if edu in string:
print(edu)
edu_set.append(edu)
return edu_set
.经过长时间的讨论,我们澄清了以下问题: 我有一个名为totaleducation.txt的文本文件和另一个名为sample.txt的text/csv文件;我想在totaleducation.txt中找到sample.txt中也存在的每个单词 因此,您应该逐行阅读totaleducation.txt,并检查sample.txt的任何一行中是否存在这些行 调用match将为您提供totaleducation.txt中的所有单词,这些单词也存在于sample.txt的任何一行中 请注意.strip“\n”。在文件1中说你有“理学硕士”,在文件2中说你有“计算机科学硕士”。如果省略.strip“\n”,则无法验证“MSc”是否在“MSc计算机科学”中;因为实际上这两行是'MSc\n'和'MSc Computer Science\n',第一行不在第二行 第二种方法是,如果文件不太大,不会导致内存问题,那么:
def match():
words = []
with open('totaleducation.txt', 'r') as f1:
for edu in f1:
with open('sample.txt', 'r') as f2:
for string in f2:
if edu.strip('\n') in string.strip('\n'):
words.append(edu.strip('\n'))
return words
也许你想用另一种方式来比较?如果edu中的字符串:否,它不起作用,它将返回[]编辑您的问题,以包括您要传递到函数中的字符串值,以及您希望匹配的输入文件中的示例行。如果您的问题不清楚,请输入更多内容,如代码和示例输入和文件content@johnII谢谢你,但是它没有得到正确的答案result@JayPratapPandey让我们努力吧。让我们坚持我提到的第二种方式。你能运行它,给我一些,比如10个教育元素和样本吗?
def match():
words = []
with open('totaleducation.txt', 'r') as f1:
for edu in f1:
with open('sample.txt', 'r') as f2:
for string in f2:
if edu.strip('\n') in string.strip('\n'):
words.append(edu.strip('\n'))
return words
education = []
with open('totaleducation.txt', 'r') as f1:
for line in f1:
education.append(line.strip('\n'))
sample = []
with open('sample.txt', 'r') as f2:
for line in f2:
sample.append(line.strip('\n'))
match = [e for e in education for s in sample if e in s]