1

Python は初めてで、皆さんが私に助けてくれることを望んでいました。

私は第一次世界大戦に関する本を持っており、国が本に登場する回数を数えたいと思っています。これまでのところ、私はこれを持っています:

>>> from __future__ import division 
>>> import nltk, re, pprint
>>> from urllib import urlopen
>>> url = "http://www.gutenberg.org/files/29270/29270.txt"
>>> raw = urlopen(url).read() 
>>> type(raw)
<type 'str'>
>>> len(raw)
1067008
>>> raw[:75]
'The Project Gutenberg EBook of The Story of the Great War, Volume II (of\r\nV'
>>>

トークン化。文字列を単語と句読点に分割します。

>>> tokens = nltk.word_tokenize(raw)
>>> type(tokens)
<type 'list'>
>>> len(tokens)
189743
>>> tokens[:10] //vind de eerste 10 tokens
['The', 'Project', 'Gutenberg', 'EBook', 'of', 'The', 'Story', 'of', 'the', 'Great']
>>>

本の始めと終わりを修正する

    >>> raw.find("PART I")
    >>> 2629
    >>> raw.rfind("End of the Project Gutenberg")
    >>> 1047663
    >>> raw = raw[2629:1047663]
    >>> raw.find("PART I")
    >>> 0

残念ながら、この本をワードカウントに実装する方法がわかりません。私の理想的な結果は次のようになります。

Germany 2000
United Kingdom 1500
USA 1000
Holland 50
Belgium 150

助けてください!

4

1 に答える 1

1

Pythonには、文字列内の部分文字列をカウントするための組み込みメソッドがあります。

from urllib import urlopen

url = "http://www.gutenberg.org/files/29270/29270.txt"
raw = urlopen(url).read()
raw = raw[raw.find("PART I"):raw.rfind("End of the Project Gutenberg")]

countries = ['Germany', 'United Kingdom', 'USA', 'Holland', 'Belgium']
for c in countries:
    print c, raw.count(c)

を生成します

Germany 117
United Kingdom 0
USA 0
Holland 10
Belgium 63

編集:eumiroは正しいです。正確な単語を数えたい場合、これは機能しません。正確な単語を検索する場合は、これを使用します。

import re
from urllib import urlopen

url = "http://www.gutenberg.org/files/29270/29270.txt"
raw = urlopen(url).read()
raw = raw[raw.find("PART I"):raw.rfind("End of the Project Gutenberg")]

for key, value in {c:len(re.findall(c + '[^A-Za-z]', raw)) for c in countries}.items():
    print key, value

編集:行番号が必要な場合:

from urllib import urlopen
import re
from collections import defaultdict

url = "http://www.gutenberg.org/files/29270/29270.txt"
raw = urlopen(url).readlines()

count = defaultdict(list)
countries = ['Germany', 'United Kingdom', 'USA', 'Holland', 'Belgium']
for c in countries:
    for nr, line in enumerate(raw):
        if re.search(c + r'[^A-Za-z]', line):
            count[c].append(nr + 1) #nr + 1 so the first line is 1 instead of 0
    print c, len(count[c]), 'lines:', count[c]
于 2012-06-05T08:54:24.620 に答える