【问题标题】:Position of query word查询词的位置
【发布时间】:2016-05-16 03:53:50
【问题描述】:

我目前正在使用 python 并使用 NLTK 来提取我的数据的特征。我要提取的一个特征是特定查询词在句子中的位置。 为此,我尝试了

String.find(word)

但它给了我比文本中的总字数更多的字。

请给我一些方法来找到单词中特定单词的位置。

例如“今天是我的生日” 单词生日的位置是4。怎么办?

【问题讨论】:

    标签: python nltk


    【解决方案1】:
    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'
    

    【讨论】:

    • 当我应用拆分时,它给了我错误 Traceback(最近一次调用最后):文件“C:\Users\user\workspace\test1\test1\final.py”,第 36 行,在 fdist2=fdist1.split("earthquake") AttributeError: 'list' object has no attribute 'split'
    • 什么是 fdlist1?在您的原始句子字符串上使用拆分。然后对该分割的结果使用索引。
    • split 也用于在空白处分割字符串。 index 是用于在单词列表中查找特定单词的方法。
    • 我该如何解决这个错误?句子中不存在特定词。? words1=words.index("earthquake" ) ValueError: 'earthquake' 不在列表中
    • 查看附加编辑。顺便说一句。如果我帮助了你,请接受我的回答;)
    【解决方案2】:

    搜索世界后,您可以使用 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 这样的内置名称作为变量名!)
    • 感谢亚历克西斯,如果我使用 word2,打印行将是:print words2.index(word) + 1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 2014-07-02
    • 2017-09-07
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多