【发布时间】:2020-04-27 08:45:51
【问题描述】:
我是 python 新手。我在多个文本文件中有一组字符串。那里我将超过 100 个文件。
cool.add.odd.inn.txt
weather: cool.add.odd.inn
blab: name= hello.add.COPY_HI
blab: name= hello.add.ACCESS_HELLO
blab: name= hello.add.ADD_HI
blab: name= hello.add.WRITE_HI
blab: name= hello.add.WRITE
blab: name= hello.add.COPY
warm.add.minus.txt
weather: warm.add.minus
blab: name= hello.add.COPY_HI
blab: name= hello.add.ACCESS_HELLO
blab: name= hello.add.ADD_HI
blab: name= hello.add.WRITE_HI
blab: name= hello.add.WRITE
blab: name= hello.add.COPY
我创建了一个模式匹配列表
total = ['WRITE_HI', 'COPY_HI', 'ADD_HI'] #there will more than 100 key words
我想要给定输入列表的完全匹配并写入 csv 文件。 查看我的编码
state1='weather,state'
weather= os.listdir('./data/weather')
for warm in weather:
file= open('./data/weather' + warm, 'r')
ins=file.read()
state1+=warm.replace('.txt', '') + ','
for all_1 in total:
if all_1 in ins:
state1 += all_1 + '\n'
state1 += '","'
输出以 csv 格式提供,现在使用我的代码,我通过字符串比较获得部分输出。这里它的匹配和相似的词(例如:我只想要'WRITE_HI'和'COPY_HI'根据我的列表但它也给出'WRITE'和'COPY'作为类似的字符串匹配我不想要那个.我只想要列表中的模式。我听说还有更多的模式匹配方法,如回归匹配等。请任何人帮助我解决这个问题。提前谢谢
Output:
weather,state
cool.add.odd.inn,'WRITE_HI'
'WRITE'
'COPY_HI'
'COPY'
'ADD_HI'
warm.add.minus,'WRITE_HI'
'WRITE'
'COPY_HI'
'COPY'
'ADD_HI'
更新:找到以下结果
def word_check(ins, total):
total=total[:]
found=[]
for match in re.finditer('\w+', ins):
if words in total:
found.append(words)
total.remove(words)
return found
【问题讨论】:
标签: python regex python-3.x list python-2.7