根據以下回應編輯問題:計數字符串
我有一個文本文件中的字符串列表。我想在另一個文本文件中計算這些字符串的出現次數。
這裏是一個字符串的一個例子,我有一個文件
Red Car
No lake
Newjersey turnpike
這裏是文本文件,我想搜索上面提到的字符串:
I have a red car which I drove on newjersey
turnpike. When I took exit 39 there was no
lake. I drove my car on muddy roads which turned my red
car into brown. Driving on Newjersey turnpike can be confusing.
我要找的答案是:
Newjersey turnpike 2
No lake 1
red car 2
如何在python中編程?非常感謝你的幫助!
這裏是我試過到目前爲止:
input_file_path = r'input_file.txt'
phrase_path = r'phrase_words.txt'
string_count_path =r'string_count.txt'
f = open(phrase_path,'r')
lines = f.readlines()
keys = []
for line in lines:
key.append(line)
phrase_word = map(string.strip,map(str.lower,keys))
f.close()
dict={}
for key in phrase_words:
dict[key]=0
f=open(input_file_path,'r')
lines = map(string.strip,map(str.lower,f.readlines()))
for w in lines:
try:
dict[w] += 1
except KeyError:
pass
f.close()
中的字符串得到妥善分配,但心不是回答正確的..
phrase_words = ['red car', 'no lake', 'newjersey turnpike']
lines = ['i have a red car which i drove on newjersey', 'turnpike. when i took exit 39 there was no', 'lake. i drove my car on muddy roads which turned my red', 'car into brown. driving on newjersey turnpike can be confusing.']
dict = {'red car': 0, 'newjersery turnpike': 0, 'no lake': 0}
你嘗試過這麼遠嗎?此外,這聽起來像功課,如果是這樣的話應該被標記。 –
'str.count()'(http://docs.python.org/library/stdtypes.html#str.count) – tMC
tmc..pls讀最後的風格..我試過了..把所有的東西都放在一起是我迷失的地方。 – Zenvega