我正在尝试编写一个脚本,该脚本将遍历我的语料库,其中包含93,000个txt文件,并找到存在于它们中的所有字母的频率分布(因此不是单独的频率分布,而是整个语料库的一个频率分布)。我已经了解到它可以对语料库中的单个文件进行频率分配,但是根本不具备进一步获取知识的技能。这是代码:
import nltk
import re
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
from nltk import FreqDist
corpus_root = '/Users/jolijttamanaha/Python/CRspeeches'
speeches = PlaintextCorpusReader(corpus_root, '.*\.txt')
print "Finished importing corpus"
f = speeches.open('Mr. THOMPSON of Pennsylvania.2010-12-07.2014sep17_at_233337.txt')
raw = f.read()
tokens = nltk.word_tokenize(raw)
tgs = nltk.trigrams(tokens)
fdist = nltk.FreqDist(tgs)
for k,v in fdist.items():
print k,v
Run Code Online (Sandbox Code Playgroud)
预先感谢您的帮助。
我有一系列字符串,类似于"2014年12月27日星期六",我想折腾"星期六"并保存名为"141227"的文件,即年+月+日.到目前为止,一切都在工作,除了我无法获得daypos或yearpos上班的正则表达式.他们都给出了同样的错误:
回溯(最近一次调用最后一次):文件"scrapewaybackblog.py",第17行,在daypos = byline.find(re.compile("[AZ] [az]*\s"))TypeError:期望一个字符缓冲区对象
什么是字符缓冲对象?这是否意味着我的表达有问题?这是我的脚本:
for i in xrange(3, 1, -1):
page = urllib2.urlopen("http://web.archive.org/web/20090204221349/http://www.americansforprosperity.org/nationalblog?page={}".format(i))
soup = BeautifulSoup(page.read())
snippet = soup.find_all('div', attrs={'class': 'blog-box'})
for div in snippet:
byline = div.find('div', attrs={'class': 'date'}).text.encode('utf-8')
text = div.find('div', attrs={'class': 'right-box'}).text.encode('utf-8')
monthpos = byline.find(",")
daypos = byline.find(re.compile("[A-Z][a-z]*\s"))
yearpos = byline.find(re.compile("[A-Z][a-z]*\D\d*\w*\s"))
endpos = monthpos + len(byline)
month = byline[monthpos+1:daypos]
day = byline[daypos+0:yearpos]
year = byline[yearpos+2:endpos]
output_files_pathname = 'Data/' # path where output will go
new_filename = year + month + day + ".txt"
outfile = …Run Code Online (Sandbox Code Playgroud) 我是编码和Python的新手,所以如果这是一个愚蠢的问题我会道歉.我想要一个遍历所有19,000个搜索结果页面的脚本,并为每个网址抓取所有网址.我已经完成了所有的报废工作,但无法弄清楚如何处理页面使用AJAX进行分页的事实.通常我只是使用url创建一个循环来捕获每个搜索结果,但这是不可能的.这是页面:http://www.heritage.org/research/all-research.aspx?cars&category = report
这是我到目前为止的脚本:
with io.open('heritageURLs.txt', 'a', encoding='utf8') as logfile:
page = urllib2.urlopen("http://www.heritage.org/research/all-research.aspx?nomobile&categories=report")
soup = BeautifulSoup(page)
snippet = soup.find_all('a', attrs={'item-title'})
for a in snippet:
logfile.write ("http://www.heritage.org" + a.get('href') + "\n")
print "Done collecting urls"
Run Code Online (Sandbox Code Playgroud)
显然,它会刮掉结果的第一页,仅此而已.
我已经看了几个相关的问题,但似乎没有人使用Python,或者至少不是以我能理解的方式.预先感谢您的帮助.
I'm trying to write a script that will go through a list of urls and scrape the web page connected to that url and save the contents to a text file. Unfortunately, a few random urls lead to a page that isn't formatted in the same way and that gets me an IndexError. How do I write a script that will just skip the IndexError and move onto the next URL? I tried the code below but just get syntax …
python ×4
ajax ×1
html ×1
html-parsing ×1
indexing ×1
nltk ×1
pagination ×1
regex ×1
selenium ×1