簡體   English   中英

從python中的文本文件中計算列表中出現和不出現特殊字符的所有元素

[英]Count all occurrences of elements with and without special characters in a list from a text file in python

如果以前已經回答過這個問題,我真的很抱歉,但是我一直在搜索SO和Google幾個小時,以了解如何正確執行此操作。 這應該很容易,我知道我缺少一些簡單的東西。

我正在嘗試從文件中讀取內容並計算列表中元素的所有出現次數。 但是,這個列表並不只是完整的單詞。 它也需要具有特殊字符和標點符號。

這是到目前為止,我一直在嘗試各種方法,而這篇文章使我最接近: Python-查找文本文件中單詞列表的單詞頻率

所以我有一個包含幾個段落的文件,我的字符串列表是:

listToCheck = ['the','The ','the,','the;','the!','the\'','the.','\'the']

我的完整代碼是:

#!/usr/bin/python

import re
from collections import Counter

f = open('text.txt','r')
wanted = ['the','The ','the,','the;','the!','the\'','the.','\'the']
words = re.findall('\w+', f.read().lower())
cnt = Counter()


for word in words:
  if word in wanted:
    print word
    cnt[word] += 1

print cnt

到目前為止,我的輸出看起來像:

the
the
the
the
the
the
the
the
the
the
the
the
the
the
the
the
the
Counter({'the': 17})

它使用標點符號計數我的“ the”字符串,但不將其作為單獨的計數器計數。 我知道是因為\\ W +。 我只是不確定在這里使用什么合適的正則表達式模式,或者我是否打算使用錯誤的方式。

我懷疑您的特定問題可能還有一些其他細節,為簡單起見,在此不再贅述。 但是,我假設您要查找的是找到給定的單詞,例如“ the”,該單詞可以具有大寫或小寫的首字母,並且可以在其前后加上空格或標點符號;,。!'等字符。 您要計算該常規模式的所有不同實例的數量。

我將定義一個單個(非析取式)正則表達式來定義它。 像這樣

import re
pattern = re.compile(r"[\s',;.!][Tt]he[\s.,;'!]")

(一般來說,這可能與您所尋找的不完全相同。我只是假設它基於您上面所說的內容。)

現在,假設我們的文字是

text = '''
Foo and the foo and ;the, foo. The foo 'the and the;
and the' and the; and foo the, and the. foo.
'''

我們可以做

matches = pattern.findall(text)

比賽將在哪里

[' the ',
 ';the,',
 ' The ',
 "'the ",
 ' the;',
 " the'",
 ' the;',
 ' the,',
 ' the.']

然后,您只需數數即可。

from collections import Counter
count = Counter()
for match in matches:
    count[match] += 1

在這種情況下會導致

Counter({' the;': 2, ' the.': 1, ' the,': 1, " the'": 1, ' The ': 1, "'the ": 1, ';the,': 1, ' the ': 1})

正如我剛開始所說的那樣,這可能並不是您想要的,但是希望您可以對其進行修改以獲得所需的內容。

補充一點,使用析取正則表達式(例如

'the|the;|the,|the!'

是像“ the”和“ the;”這樣的字符串 也將匹配第一個選項,即“ the”,並將其作為匹配項返回。 即使可以通過更仔細地選擇選項來避免此問題,但我認為總體上可能並不容易。

最簡單的選擇是將所有“需要的”字符串組合成一個正則表達式:

rr = '|'.join(map(re.escape, wanted)) 

然后使用re.findall查找文本中的所有匹配re.findall

要確保更長的st先匹配,只需將wanted列表按長度排序:

wanted.sort(key=len, reverse=True)
rr = '|'.join(map(re.escape, wanted)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM