Skip to main content
 首页 » 编程设计

python之从两个文件中提取相同的行,同时忽略小写/大写

2025年05月04日17freeliver54

目的是从两个文件中提取相同的行,同时忽略大小写和标点符号

我有两个文件

源文件.txt

Foo bar 
blah blah black sheep 
Hello World 
Kick the, bucket 

processed.txt

foo bar 
blah sheep black 
Hello world 
kick the bucket , 

期望的输出(来自 source.txt):

Foo bar 
 
Hello World 
Kick the, bucket 

我一直这样做:

from string import punctuation 
with open('source.txt', 'r') as f1, open('processed.txt', 'r') as f2: 
  for i,j in zip(f1, f2): 
    lower_depunct_f1 = " ".join("".join([ch.lower() for ch in f1 if f1 not in punctuation]).split()) 
    lower_depunct_f2 = " ".join("".join([ch.lower() for ch in f2 if f2 not in punctuation]).split()) 
    if lower_depunct_f1 == lower_depunct_f2: 
      print f1 
    else: 
      print 

有没有办法用 bash 工具做到这一点? perl、shell、awk、sed?

请您参考如下方法:

使用 awk 更容易做到这一点:

awk 'FNR==NR {s=toupper($0); gsub(/[[:blank:][:punct:]]+/, "", s); a[s]++;next} 
   {s=toupper($0); gsub(/[[:blank:][:punct:]]+/, "", s); print (s in a)?$0:""}' file2 file1 
Foo bar 
 
Hello World 
Kick the, bucket