文字列のリストに単語が何回出現するかを数える方法は?
例えば:
['This is a sentence', 'This is another sentence']
単語「文」の結果は 2 です
文字列のリストに単語が何回出現するかを数える方法は?
例えば:
['This is a sentence', 'This is another sentence']
単語「文」の結果は 2 です
オブジェクトを使用して、collections.Counter()
空白で単語を分割します。おそらく単語も小文字にし、句読点を削除したいでしょう:
from collections import Counter
counts = Counter()
for sentence in sequence_of_sentences:
counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())
または、単語の文字のみに一致する正規表現を使用することもできます。
from collections import Counter
import re
counts = Counter()
words = re.compile(r'\w+')
for sentence in sequence_of_sentences:
counts.update(words.findall(sentence.lower()))
counts
これで、単語ごとのカウントを持つ辞書ができました。
デモ:
>>> sequence_of_sentences = ['This is a sentence', 'This is another sentence']
>>> from collections import Counter
>>> counts = Counter()
>>> for sentence in sequence_of_sentences:
... counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())
...
>>> counts
Counter({'this': 2, 'is': 2, 'sentence': 2, 'a': 1, 'another': 1})
>>> counts['sentence']
2
少しの正規表現と辞書を使用して、必要なことを簡単に行うことができます。
import re
dict = {}
sentence_list = ['This is a sentence', 'This is a sentence']
for sentence in sentence_list:
for word in re.split('\s', sentence): # split with whitespace
try:
dict[word] += 1
except KeyError:
dict[word] = 1
print dict