我在Python中很新。我有两种文件进行比较。Python:通过几个文件进行字符串比较,但只找到了很多可能的最后一个
第一类型的输出 - dict.txt - 是:
1_A
2_B
3_C
第二类型的输出 - 1_1h.txt - 是:
K
P
A
B
C
E
我试图做一个通过与正则表达式隔离dict.txt中的字母来比较(稍后,我还将使用该字母旁边的数字来了解文件中字母本身的位置/行),并将该字母与字母中的字母进行比较每个1_1h.txt文件类型。
但我有一个问题:它无法识别所有匹配的表达式,但只有一个....为什么? 在这个例子中有2场比赛: 'K' 和 'C',但输出显示只是 'C' 和许多空间... 这里是我的代码:
import os
import re
import fileinput
dict_file = open("C:\\Users\\KP\\Desktop\\test\\dict.txt", "r")
dictionary = dict_file.read().split('\n')
#print lines
#print len(lines)
dict_file.close()
for file in os.listdir('C:\\Users\\KP\\Desktop\\test'):
if file == '1_1h.txt':
open(file)
for w in dictionary:
regex = re.compile('(\d)_(.*)')
res = regex.search(w)
if res:
nb_w = int(res.group(1))
content_w = str(res.group(2))
for line in fileinput.input(["1_1h.txt"]):
print(content_w+"-->"+line)
if str(line) == str(content_w):
print('match '+line)
输出:
runfile('C:/Users/KP/Desktop/test/testlocale.py', wdir='C:/Users/KP/Desktop/test')
F-->K
F-->J
F-->C
K-->K
K-->J
K-->C
C-->K
C-->J
C-->C
match C
您好,谢谢,我得到这个错误 解析度= re.findall(W,正则表达式) 文件 “C:\ Python27 \ LIB \ re.py”,线路181,在的findall 回报_compile(图案,标志).findall(串) 类型错误:预期的字符串或缓冲区 – Jurafsky
请接受的答案,如果它解决您的问题 –
我仍然得到这个错误,我不知道如何处理它 '水库= re.findall(w,regex)文件“C:\ Python27 \ lib \ re.py”,第181行,在findall中返回_compile(pattern,flags)。findall(字符串)TypeError:期望的字符串或缓冲区' – Jurafsky