【发布时间】:2016-01-06 05:29:42
【问题描述】:
我正在计算某组总统演讲中的收缩次数,并希望将这些收缩输出到 CSV 或文本文件中。这是我的代码:
import urllib2,sys,os,csv
from bs4 import BeautifulSoup,NavigableString
from string import punctuation as p
from multiprocessing import Pool
import re, nltk
import requests
import math, functools
import summarize
reload(sys)
def processURL_short(l):
open_url = urllib2.urlopen(l).read()
item_soup = BeautifulSoup(open_url)
item_div = item_soup.find('div',{'id':'transcript'},{'class':'displaytext'})
item_str = item_div.text.lower()
return item_str
every_link_test = ['http://www.millercenter.org/president/obama/speeches/speech-4427',
'http://www.millercenter.org/president/obama/speeches/speech-4424',
'http://www.millercenter.org/president/obama/speeches/speech-4453',
'http://www.millercenter.org/president/obama/speeches/speech-4612',
'http://www.millercenter.org/president/obama/speeches/speech-5502']
data = {}
count = 0
for l in every_link_test:
content_1 = processURL_short(l)
for word in content_1.split():
word = word.strip(p)
if word in contractions:
count = count + 1
splitlink = l.split("/")
president = splitlink[4]
speech_num = splitlink[-1]
filename = "{0}_{1}".format(president,speech_num)
data[filename] = count
print count, filename
with open('contraction_counts.csv','w',newline='') as fp:
a = csv.writer(fp,delimiter = ',')
a.writerows(data)
运行 for 循环打印出来
79 obama_speech-4427
101 obama_speech-4424
101 obama_speech-4453
182 obama_speech-4612
224 obama_speech-5502
我想将其导出到一个文本文件,其中左侧的数字是一列,总统/演讲编号在第二列。我的with 语句只是将每一行写入一个单独的文件,这绝对不是最佳的。
【问题讨论】:
-
如果你用谷歌搜索
write csv with python,你会得到很多答案,try this one -
是的,我已经看到了。 CSV 的输出基本上在每列中放置一个字母,甚至不包括收缩计数。
-
我建议编辑这个问题或创建一个关于您尝试用于输出 CSV 的代码的新问题 - 我们帮助您处理您已经尝试过的代码比我们更简单从头开始给你写点东西。
-
我试过的代码在上面代码的尾部。它以
with open('contraction_counts.csv'...开头
标签: python csv for-loop beautifulsoup output