これが私がしたことです。質問は最後になります。
1)最初にopen().read()
、次のように関数を実行するために使用して.txtドキュメントを開きました。
def clean_text_passage(a_text_string):
new_passage=[]
p=[line+'\n' for line in a_text_string.split('\n')]
passage = [w.lower().replace('</b>\n', '\n') for w in p]
if len(passage[0].strip())>0:
if len(passage[1].strip())>0:
new_passage.append(passage[0])
return new_passage
2)返さnew_passage
れたを使用して、次のコマンドを使用して単語を単語の行に変換しました。
newone = "".join(new_passage)
3)次に、次のように別の関数を実行しました。
def replace(filename):
match = re.sub(r'[^\s^\w+]risk', 'risk', filename)
match2 = re.sub(r'risk[^\s^\-]+', 'risk', match)
match3 = re.sub(r'risk\w+', 'risk', match2)
return match3
この時点まで、すべての言葉は問題ありません。ここに問題があります。印刷するときmatch3
:
i agree to the following terms regarding my employment or continued employment
with dell computer corporation or a subsidiary or affiliate of dell computer
corporation (collectively, "dell").
単語が並んでいるように見えます。だが、
4)最後の関数convert = count_words(match3)
を次のように実行しました。
def count_words(newstring):
from collections import defaultdict
word_dict=defaultdict(int)
for line in newstring:
words=line.lower().split()
for word in words:
word_dict[word]+=1
印刷するとword_dict
、次のように表示されます。
defaultdict(<type 'int'>, {'"': 2, "'": 1, '&': 4, ')': 3, '(': 3, '-': 4, ',': 4, '.': 9, '1': 7, '0': 8, '3': 2, '2': 3, '5': 2, '4': 2, '7': 2, '9': 2, '8': 1, ';': 4, ':': 2, 'a': 67, 'c': 34, 'b': 18, 'e': 114, 'd': 44, 'g': 15, 'f': 23, 'i': 71, 'h': 22, 'k': 10, 'j': 2, 'm': 31, 'l': 43, 'o': 79, 'n': 69, 'p': 27, 's': 56, 'r': 72, 'u': 19, 't': 81, 'w': 4, 'v': 3, 'y': 16, 'x': 3})
私のコードの目的は特定の単語を数えることなので、「I」、「l」、「i」の代わりに「リスク」のような単語を行に含める必要があります(つまり、リスクを取るのが好きです)。
質問:1行の単語を数えることができるようにmatch3
、使用するのと同じ方法で単語を含めるにはどうすればよいですか?readlines()
match3
.txtファイルとして保存し、を使用して再度開いてreadlines()
から、カウント関数を実行すると、正常に機能します。保存して再度開くことなく動作させる方法を知りたいreadlines()
ですか?
ありがとう。眠れるようにこれを理解できたらいいのにと思います。