【问题标题】:Python re.sub, re.split fails splitting up words in long passagePython re.sub,re.split 无法在长段落中拆分单词
【发布时间】:2014-10-02 14:06:36
【问题描述】:

我正在尝试从存储在光盘上的 HTML 文档中创建一个单词列表。当我尝试拆分单词并将它们添加到我的单词向量中时,我最终会弄得一团糟。

 def get_word_vector(self):
  line = self.soup.get_text()
  re.sub("s/(\\u[a-e0-9][a-e0-9][a-e0-9]//|\\n)","",line)
  for word in line.split("\s+"):
   for the_word in word.split("[,.\"\\/?!@#$%^&*\{\}\[\]]+"):
    if the_word not in self.word_vector:
     self.word_vector[the_word]=0
    self.word_vector[the_word]+=1
    self.doc_length=self.doc_length+1
  for keys in self.word_vector:
   print "%r: %r" % (keys, self.word_vector[keys]) #So I can see whats happening

在我得到的 wiki 页面上进行测试时(小样本):

"Horse Markings"\n"Horse and Pony Head Markings"\n"Horse and Pony Leg Markings"\n"Identifying Horse parts and markings," Adapted From: Horses For Dummies, 2nd Edition.\n\n\n\n\n\n\n[hide]

作为一个单一的“词”。该文档正在被 BS4 读取,例如:

  self.soup = BeautifulSoup(open(fullpath,"r"))

我不明白为什么会这样。我猜正则表达式失败是因为它错了???

【问题讨论】:

  • 所以,基本上,您需要获取网页的单词列表,对吧?

标签: python regex python-2.7 beautifulsoup


【解决方案1】:

只是另一种选择:通过get_text() 获取文本,然后使用nltk.tokenize 从文本中获取单词列表。这里的重点不是重新发明轮子,而是针对特定工作使用专门的工具:BeautifulSoup 用于 HTML 解析,nltk 用于文本处理:

from urllib2 import urlopen
from bs4 import BeautifulSoup
from nltk.tokenize import RegexpTokenizer

soup = BeautifulSoup(urlopen('http://en.wikipedia.org/wiki/Stack_Overflow'))
tokenizer = RegexpTokenizer(r'\w+')
print tokenizer.tokenize(soup.get_text())

打印:

[u'Stack', u'Overflow', u'Wikipedia', u'the', u'free', u'encyclopedia', ... ]

【讨论】:

  • 谢谢先生。我想如果有人真的为此目的制作了一个库,那么问如何去做是愚蠢的。但是你有没有看到我的正则表达式看起来有问题?
  • @jasondancks 好吧,至少,re.sub() 调用不会修改字符串,您需要将它的结果分配给line
  • @jasondancks plus,而不是line.split(),你应该使用re.split()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多