Bash/Python:openurl&;打印前10个单词
我需要使用管道(以及任何需要的附加python脚本)从文本中提取10个最常见的单词;输出是由空格分隔的所有大写字组成的块。 这个管道需要从任何外部文件中提取文本:我已经设法让它处理.txt文件,但我还需要能够输入URL,并让它做同样的事情 我有以下代码:Bash/Python:openurl&;打印前10个单词,python,bash,pipe,Python,Bash,Pipe,我需要使用管道(以及任何需要的附加python脚本)从文本中提取10个最常见的单词;输出是由空格分隔的所有大写字组成的块。 这个管道需要从任何外部文件中提取文本:我已经设法让它处理.txt文件,但我还需要能够输入URL,并让它做同样的事情 我有以下代码: alias words="tr a-zA-Z | tr -cs A-Z | tr ' ' '\012' | sort -n | uniq -c | sort -r | head -n 10 | awk '{printf \"%s \", \$
alias words="tr a-zA-Z | tr -cs A-Z | tr ' ' '\012' | sort -n | uniq -c |
sort -r | head -n 10 | awk '{printf \"%s \", \$2}END{print \"\"}'" (on one line)
通过cat hamlet.txt | words
可以告诉我:
TO THE AND A 'TIS THAT OR OF IS
更复杂的是,我需要排除任何“功能”词:这些是“非词汇”词,如“a”、“the”、“of”、“is”、任何代词(I、you、him)和任何介词(there、at、from)
我需要能够键入htmlstriphttp://www.google.com.au |words
并按上述方式打印出来
对于URL打开:
我试图弄明白的python脚本(我们称之为htmlstrip)从文本中去掉任何标记,只留下“人类可读”的文本。这应该能够打开任何给定的URL,但我不知道如何让它工作。
到目前为止,我所拥有的:
import re
import urllib2
filename = raw_input('File name: ')
filehandle = open(filename)
html = filehandle.read()
f = urllib2.urlopen('http://') #???
print f.read()
text = [ ]
inTag = False
for ch in html:
if ch == '<':
inTag = True
if not inTag:
text.append(ch)
if ch == '>':
inTag = False
print ''.join(text)
重新导入
导入urllib2
文件名=原始输入('文件名:')
filehandle=open(文件名)
html=filehandle.read()
f=urllib2.urlopen('http://')#???
打印f.read()
text=[]
inTag=False
对于html格式的ch:
如果ch='':
inTag=False
打印“”。加入(文本)
我知道这既不完整,也可能不正确-任何指导都将不胜感激。为此使用
re.sub
:
import re
text = re.sub(r"<.+>", " ", html)
重新导入
text=re.sub(r“”,html)
对于脚本等特殊情况,您可以包括正则表达式,例如:
<script.*>.*</script>
*
您可以像这样使用和正则表达式:
#!/usr/bin/env python
from scrape import s
import sys, re
if len(sys.argv) < 2:
print "Usage: words.py url"
sys.exit(0)
s.go(sys.argv[1]) # fetch content
text = s.doc.text # extract readable text
text = re.sub("\W+", " ", text) # remove all non-word characters and repeating whitespace
print text
#/usr/bin/env python
从垃圾进口
导入系统,re
如果len(系统argv)<2:
打印“用法:words.py url”
系统出口(0)
s、 go(sys.argv[1])#获取内容
text=s.doc.text#提取可读文本
text=re.sub(“\W+”,“”,text)#删除所有非单词字符和重复的空白
打印文本
然后就是:
/words.pyhttp://whatever.com
更新:抱歉,请阅读关于纯Python的评论,不带任何附加模块。是的,在这种情况下,我认为重新开始是最好的办法
也许使用pycURL
比通过re
删除标记更容易、更正确
from StringIO import StringIO
import pycurl
url = 'http://www.google.com/'
storage = StringIO()
c = pycurl.Curl()
c.setopt(c.URL, url)
c.setopt(c.WRITEFUNCTION, storage.write)
c.perform()
c.close()
content = storage.getvalue()
print content
您可能应该看看BeautifulSoup,了解如何下载HTML页面并将其拆分为人类可读的页面。这是一个常见问题;另见,例如和。。。或者,如果您不特别喜欢为此使用Python,
lynx-dumphttp://page.example.com/ |单词
:(不幸的是,对于这个特殊任务,我需要使用Python,没有外部模块。不过,我会看看其他帖子,谢谢!不会删除内联css和javascript@Jeff:不,不会。我同意triplee的观点,这里最好的方法是使用实际的html解析器。显然OP不想使用任何“外部模块”但是,您可以将下面的所有内容替换为一行:text=re.sub(“\W+”,“”,text)