![](/img/trans.png)
[英]How to open multiple terminals and execute command in each terminal then save the output from each terminal to a one variable or a file
[英]How to save multiple output in multiple file where each file has a different title coming from an object in python?
我正在從網站( http://www.gfrvitale.altervista.org/index.php/autismo-in?format=feed&type=rss )中抓取RSS提要。 我寫下了一個腳本,從每個提要中提取和純化文本。 我的主要問題是將每個項目的每個文本保存在不同的文件中,我還需要使用每個項目的正確標題摘錄來命名每個文件。 我的代碼是:
for item in myFeed["items"]:
time_structure=item["published_parsed"]
dt = datetime.fromtimestamp(mktime(time_structure))
if dt>t:
link=item["link"]
response= requests.get(link)
doc=Document(response.text)
doc.summary(html_partial=False)
# extracting text
h = html2text.HTML2Text()
# converting
h.ignore_links = True #ignoro i link
h.skip_internal_links=True #ignoro i link esterni
h.inline_links=True
h.ignore_images=True #ignoro i link alle immagini
h.ignore_emphasis=True
h.ignore_anchors=True
h.ignore_tables=True
testo= h.handle(doc.summary()) #testo estratto
s = doc.title()+"."+" "+testo #contenuto da stampare nel file finale
tit=item["title"]
# save each file with it's proper title
with codecs.open("testo_%s", %tit "w", encoding="utf-8") as f:
f.write(s)
f.close()
錯誤是:
File "<ipython-input-57-cd683dec157f>", line 34 with codecs.open("testo_%s", %tit "w", encoding="utf-8") as f:
^
SyntaxError: invalid syntax
您需要在%tit
之后加上逗號
應該:
#save each file with it's proper title
with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
f.close()
但是,如果您的文件名包含無效字符,它將返回錯誤(即[Errno 22]
)
您可以嘗試以下代碼:
...
tit = item["title"]
tit = tit.replace(' ', '').replace("'", "").replace('?', '') # Not the best way, but it could help for now (will be better to create a list of stop characters)
with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
f.close()
使用nltk
其他方式:
from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tit = item["title"]
tit = tokenizer.tokenize(tit)
tit = ''.join(tit)
with codecs.open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
f.close()
首先,您放錯了逗號,應該在%tit
之后,而不是之前。
其次,您不需要關閉文件,因為您使用的with
語句會自動為您完成文件。 編解碼器是從哪里來的? 我在其他任何地方都看不到...。無論如何,正確的with
語句是:
with open("testo_%s" %tit, "w", encoding="utf-8") as f:
f.write(s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.