[英]Count occurences of strings from list in text file
我有一個字符串列表,例如: booknames = [Book name 1, Book name 2, Book name 3, ....]
我也有一個這樣格式的文本文件:logfile.txt
X person borrowed Book name 1 on Y date Z person borrowed Book name 2 on D date ...
我想知道每本書的借閱次數。 所以我需要計算日志文件中列表“書名”中每個元素的出現次數。 最好結果將在不同的列表中,例如:
書名 = [ A , b , c , d]
生成的列表:Occurence = [ 1 , 4 , 5 , 0]
我已經嘗試過字典方法,但是似乎沒有用,所以我一直在努力計算。
我試過的東西:
`
file = open('logfile.txt', 'r').read()
b = bookname
count = file.count(b)
print(count)
`
但這不起作用,因為 bookname 是一個列表而不是一個字符串。 因此,我的想法是創建一個 for 循環,它檢查列表 bookname 的每個元素是否出現,但是我沒有知識來創建一個可以工作的,也找不到適合我需要的
如果您有列表,那么您應該使用for
-loop 分別檢查列表中的每個元素。 結果你應該append()
來列出結果。
booknames = ['Book name 1', 'Book name 2', 'Book name 3']
occurences = []
#text = open('logfile.txt', 'r').read()
text = '''X person borrowed Book name 1 on Y date
Z person borrowed Book name 2 on D date
...'''
for name in booknames:
count = text.count(name)
occurences.append(count)
print(occurences)
結果
[1, 1, 0]
順便說一句:如果每一行都有相似的結構,那么也許你可以得到每一行並從行中截取書名並使用collections.Counter
來計算名稱。
import collections
booknames = ['Book name 1', 'Book name 2', 'Book name 3']
occurences = collections.Counter()
#fh = open('logfile.txt')
fh = '''X person borrowed Book name 1 on Y date
Z person borrowed Book name 2 on D date
...'''.splitlines()
for line in fh:
parts = line.split('borrowed', 1)
if len(parts) < 2:
print("Can't find 'borrowed' in", line)
continue
parts = parts[1].rsplit('on', 1)
if len(parts) < 0:
print("Can't find 'on' in", line)
continue
name = parts[0].strip()
print('found:', name)
occurences.update([name])
print(occurences)
結果
Found: Book name 1
Found: Book name 2
Can't find 'borrowed' in ...
Counter({'Book name 1': 1, 'Book name 2': 1})
然后你可以在Counter
使用booknames
for name in booknames:
print(name, 'occures', occurences[name], 'times')
結果
Book name 1 occures 1 times
Book name 2 occures 1 times
Book name 3 occures 0 times
或作為列表
result = []
for name in booknames:
result.append( occurences[name] )
print(result)
或更短的列表理解
result = [ occurences[name] for name in booknames ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.