我正在尝试解析一个字符串,然后在制作python字典后进行一些计算。但我遇到了问题。这就是我到目前为止所写的内容......
name = raw_input("Enter name of the file")
if len(name) < 1:
name = "test.txt"
fh = open(name)
count = dict()
new = ""
for line in fh:
line = line.rstrip()
if line.startswith("From "):
time = line.split()
time = time[5]
hr = time.split(":")
new.append(hr[0])
count[new] = count.get(new,0) + 1
print count
基本上我想读取一个文件,根据特定的模式选择一条线(在这种情况下,行以“From”开头),拆分选定的行,再次根据“:”拆分选定的行。一旦有第一列(基本上是两位数的例子 - 09,11,24,11,11,11等),然后进行数字计数,然后报告数字,然后计算数量。但是我的代码出错了。
AttributeError: 'str' object has no attribute 'append' on line 14
有任何帮助吗?
答案 0 :(得分:1)
import collections
import re
REGEX = r'^From\s+(?:\S\s){4}(\d+):.*$'
file_name = raw_input("Enter the name of the file: ")
if file_name == '':
file_name = 'test'
with open(file_name, 'r') as f:
file_content = f.read() # assuming the file isn't too large
numbers = re.findall(REGEX, file_content, re.MULTILINE)
print collections.Counter(numbers) # count '09' and '009' as different numbers
print collections.Counter([int(i) for i in numbers]) # count '09' and '009' as the same number