2017-10-13 36 views
0

我有一個文本文件,其中包含35k字的段落。下面的示例蟒蛇 - 找到文件中的匹配句子

This sentence does repeat? This sentence does not repeat! This sentence does not repeat. This sentence does repeat. 
This sentence does repeat. This sentence does not repeat! This sentence does not repeat. This sentence does repeat! 

我想識別匹配的句子。我設法找到的一種方法是使用.,!,?等作爲分隔符將段落拆分爲單獨的行,並查找匹配的行。

代碼

import collections as col 

with open('txt.txt', 'r') as f: 
    l = f.read().replace('. ','.\n').replace('? ','?\n').replace('! ','!\n').splitlines() 
print([i for i, n in col.Counter(l).items() if n > 1]) 

請提出一些更好的方法。

回答

3

您可以使用split

import re 
... 
l = re.split(r'[?!.]*',f.read()) 
+0

得到這個錯誤'sre_constants.error:沒有重複的位置0' –

+0

@VanPeer我的道歉,我犯了一個正則表達式的錯誤。我自更新了我的答案。請再試一次。 – rb612

+0

謝謝,似乎正在工作!得到這個警告信息 're.py:212:FutureWarning:split()需要一個非空的模式匹配。 return _compile(pattern,flags).split(string,maxsplit)' –

0

我無法機制保障這將是最快的,但我會嘗試利用的sort速度。首先,我會通過標點符號分割文本以列出津貼,然後在列表上運行排序以訂購所有津貼,然後循環列表並計算相同的連續津貼數量並存儲津貼和計數在一個字典。

0

你可以做一個不同的。正則表達式模塊功能非常強大:

import re 
from collections import Counter 

pat = r'(\?)|(\.)|(!)' 
c = Counter() 
with open('filename') as f: 
     for line in f: 
       c[re.sub(pat, '\n', line)] += 1 

這將創建一個正則表達式模式匹配?, . or !,並用\n替換它。 使用for循環會發生這種情況。