【问题标题】:Tokenizing a string having double quotes标记具有双引号的字符串
【发布时间】:2017-05-24 10:53:50
【问题描述】:

我有一个字符串形式:

'I am going to visit "Huge Hotel" and the "Grand River"'

我希望它被标记为

['I', 'am', 'going',..., 'Huge Hotel','and' ,'the' ,'Grand River']

正如所见,'Huge Hotel''Grand River' 被视为一个单词,因为它们出现在引号中。

import nltk
text = 'I am going to visit "Huge Hotel" and the "Grand River"'
b = nltk.word_tokenize(text)

我已经写了上面的代码,但它不起作用

【问题讨论】:

  • 如果你展示你尝试过的东西会更好。现在,这只是适合我的代码,很可能不会在这里受到欢迎。
  • 刚刚更新问题

标签: python-2.7 nlp nltk


【解决方案1】:

它看起来很奇怪,但它确实有效:

  1. re.findall('"([^"]*)"', s): 查找所有用双引号括起来的子字符串
  2. phrase.replace(' ', '_'):将步骤 1 中这些子字符串中的所有空格替换为下划线。
  3. 将所有用双引号括起来的字符串替换为第 2 步中带下划线的子字符串。
  4. 在修改后的字符串上使用word_tokenize()

[出]:

>>> import re
>>> from nltk import word_tokenize
>>> s = 'I am going to visit "Huge Hotel" and the "Grand River"'
>>> for phrase in re.findall('"([^"]*)"', s):
...     s = s.replace('"{}"'.format(phrase), phrase.replace(' ', '_'))
... 
>>> s
'I am going to visit Huge_Hotel and the Grand_River'
>>> word_tokenize(s)
['I', 'am', 'going', 'to', 'visit', 'Huge_Hotel', 'and', 'the', 'Grand_River']

我确定有一个更简单的正则表达式操作可以代替一系列正则表达式+字符串操作。

【讨论】:

  • 感谢您的帮助,但您使用了下划线 (_) 有没有办法在没有下划线的情况下做同样的事情????
  • 不,用word_tokenize 保护短语相当困难,下划线是保护短语免受标记化的少数字符之一。
  • @Saul_goodman 我建议你尝试pos 标记句子,但这也相当困难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2014-09-20
  • 2015-05-16
  • 2014-11-27
  • 1970-01-01
相关资源
最近更新 更多