【发布时间】:2016-05-16 03:53:50
【问题描述】:
我目前正在使用 python 并使用 NLTK 来提取我的数据的特征。我要提取的一个特征是特定查询词在句子中的位置。 为此,我尝试了
String.find(word)
但它给了我比文本中的总字数更多的字。
请给我一些方法来找到单词中特定单词的位置。
例如“今天是我的生日” 单词生日的位置是4。怎么办?
【问题讨论】:
我目前正在使用 python 并使用 NLTK 来提取我的数据的特征。我要提取的一个特征是特定查询词在句子中的位置。 为此,我尝试了
String.find(word)
但它给了我比文本中的总字数更多的字。
请给我一些方法来找到单词中特定单词的位置。
例如“今天是我的生日” 单词生日的位置是4。怎么办?
【问题讨论】:
string = 'Today is my birthday'
string.find('my') #Out: 9
string[9:] #Out: 'my birthday'
find 不按单词搜索字符串,而是按字符搜索。对于简单的示例,您可以这样做(注意它的索引为零):
words = string.split()
words.index('my') #Out: 2
编辑
如果您需要一个更复杂的单词定义,而不仅仅是由空格分隔的字符串,您可以使用正则表达式。这是一个简单的例子:
import re
word_re = re.compile('\w+')
words = map(lambda match: match.group(0), word_re.finditer(string))
words.index('my') #Out: 2
EDIT2
try:
words.index('earthquake')
except ValueError:
print 'handle missing word here'
【讨论】:
搜索世界后,您可以使用 re 或 nltk 将文本传输到字符串列表:
import re
text = "Today is my birthday"
word = "birthday"
words1 = re.sub("[^\w]", " ", text).split() # using re
import nltk
words2 = nltk.word_tokenize(text) # using nltk
position = 1
for str in words1 :# or for str in words2 :
if str == word:
print position
position += 1
【讨论】:
position + = 1 更改为 position += 1,因为您不能在 Add AND 赋值运算符中的 + 和 = 之间插入空格。这将导致语法错误
words2 列表后,只需获得words2.index(word) 的位置即可。 (另外:永远不要使用像 str 这样的内置名称作为变量名!)