我正在尝试做的事情:
我正在尝试在 python 中使用“打开”,这是我要执行的脚本。我正在尝试将“餐厅名称”作为输入并保存一个文件(reviews.txt)。
脚本:( 简而言之,脚本会转到一个页面并抓取评论)
from bs4 import BeautifulSoup
from urllib import urlopen
queries = 0
while queries <201:
stringQ = str(queries)
page = urlopen('http://www.yelp.com/biz/madison-square-park-new-york?start=' + stringQ)
soup = BeautifulSoup(page)
reviews = soup.findAll('p', attrs={'itemprop':'description'})
authors = soup.findAll('span', attrs={'itemprop':'author'})
flag = True
indexOf = 1
for review in reviews:
dirtyEntry = str(review)
while dirtyEntry.index('<') != -1:
indexOf = dirtyEntry.index('<')
endOf = dirtyEntry.index('>')
if flag:
dirtyEntry = dirtyEntry[endOf+1:]
flag = False
else:
if(endOf+1 == len(dirtyEntry)):
cleanEntry = dirtyEntry[0:indexOf]
break
else:
dirtyEntry = dirtyEntry[0:indexOf]+dirtyEntry[endOf+1:]
f=open("reviews.txt", "a")
f.write(cleanEntry)
f.write("\n")
f.close
queries = queries + 40
问题: 它使用附加模式“a”,根据文档,“w”是它覆盖的写入模式。当我将其更改为“w”时,没有任何反应。
f=open("reviews.txt", "w") #does not work!
实际问题: 编辑:让我清除混乱。
我只想要一个包含所有评论的review.txt文件。每次我运行脚本时,我都希望脚本根据我的输入用新的评论覆盖现有的 review.txt。
谢谢,