Python 从包含列表的不同txt文件返回匹配字符串。新行中的每个项目
我对python和一般编程都很陌生。 我有两个文本文件。每一项都是一个列表,每一项都在一个新行上 我试图找到匹配的字符串,忽略每个列表中的大小写和某些标点(“,”,“-”,“\n”)。这就是我到目前为止所做的: 基本上,我需要翻译列表项,并比较2 List1.txtPython 从包含列表的不同txt文件返回匹配字符串。新行中的每个项目,python,string,compare,Python,String,Compare,我对python和一般编程都很陌生。 我有两个文本文件。每一项都是一个列表,每一项都在一个新行上 我试图找到匹配的字符串,忽略每个列表中的大小写和某些标点(“,”,“-”,“\n”)。这就是我到目前为止所做的: 基本上,我需要翻译列表项,并比较2 List1.txt Proper Title Here A Title Here, crap B Title Here-more crap C Title Here D Title Here E Title Here List2.txt Proper
Proper Title Here
A Title Here, crap
B Title Here-more crap
C Title Here
D Title Here
E Title Here
List2.txt
Proper Title Here
B Title Here-more crap
Q Title List item
代码:
应输出:
Proper Title Here
B Title Here-more crap
读入第一个列表,删掉不需要的标点符号
data = file1.read()
data = data.lower() #make it all lowercase
data = re.sub("[,-]","",data) #replace unwanted punctuation
list1= data.splitlines()
对第二个列表执行相同的操作
data = file2.read()
data = data.lower() #make it all lowercase
data = re.sub("[,-]","",data) #replace unwanted punctuation
list2= data.splitlines()
然后只打印两个列表的交集
print "\n".join(set(list1).intersection(list2))
非常感谢您,我添加了adition re.sub以删除空白,它工作得非常完美。谢谢你的时间。
print "\n".join(set(list1).intersection(list2))