匿名用户
1级
2014-08-31 回答
代码应该不难吧。既然用爬虫爬下来了,为什么爬取数据的时候没做处理呢。
之前用过Scrapy爬虫框架,挺好用的,你可研究下。
代码:
#!coding=utf-8
import os
import re
import random
# 获取当前目录文件列表
def getNum():
flist = os.listdir(os.getcwd())
# 遍历文件
for f in flist:
if f != os.path.basename(__file__):
with open(f, 'r') as fn:
text = fn.read()
num = re.findall(r'评论人数:(\d+)', text)
print f, num
# 文件写入测试
def test():
for i in range(10):
with open('%d.txt' % i, 'w') as f:
f.write('文件:%d\n每家餐馆是一个文件,统计评论数,求读取每个文件中 “评论人数:%d” 中 的60并相加,求具体程序,60是个例子' % (i, random.randint(1, 200)))
print u'文件写入完毕'
if __name__ == '__main__':
# test()
getNum()代码基本符合要求,但健壮性有些差。你自己用的时候修改吧
测试结果:
C:\Python27\python.exe D:/11/c.py
文件写入完毕
0.txt ['131']
1.txt ['181']
2.txt ['56']
3.txt ['119']
4.txt ['18']
5.txt ['103']
6.txt ['88']
7.txt ['115']
8.txt ['160']
9.txt ['136']
Process finished with exit code 0
追问:
大神,文件路径怎么改?我没学过Python,代码都是别人给的。。
追答:
# 你把下面这句修改了
flist = os.listdir(os.getcwd())
# 改成下面的
flist = ''
print u'路径必须为全路径:如下示例'
print u'D:/test/'
flist = str(raw_input(u'输入路径,默认为当前目录'))
if list == '':
flist = os.listdir(os.getcwd())这样应该可以了
追问:
谢谢大神了