【问题标题】:Tokenizing a string gives some words merged对字符串进行标记可以合并一些单词
【发布时间】:2013-07-29 17:46:42
【问题描述】:

我使用以下代码标记一个字符串,从标准输入读取。

d=[]
cur = ''
for i in sys.stdin.readline():
    if i in ' .':
        if cur not in d and (cur != ''):
            d.append(cur)
            cur = ''
    else:
        cur = cur + i.lower()

这给了我一个不重复的单词数组。但是,在我的输出中,有些单词没有被拆分。

我的输入是

Dan went to the north pole to lead an expedition during summer.

输出数组d是

['dan', 'went', 'to', 'the', 'north', 'pole', 'tolead', 'an', '远征', 'during', 'summer']

为什么tolead在一起?

【问题讨论】:

    标签: python stdin


    【解决方案1】:

    试试这个

    d=[]
    cur = ''
    for i in sys.stdin.readline():
        if i in ' .':
            if cur not in d and (cur != ''):
                d.append(cur)
            cur = '' # note the different indentation
        else:
            cur = cur + i.lower()
    

    【讨论】:

      【解决方案2】:

      "to" 已经在 "d" 中。因此,您的循环跳过了"to""lead" 之间的空格,但继续连接;一旦它到达下一个空格,它就会发现"tolead" 不在d 中,所以它会追加它。

      更简单的解决方案;它还去除了所有形式的标点符号:

      >>> import string
      >>> set("Dan went to the north pole to lead an expedition during summer.".translate(None, string.punctuation).lower().split())
      set(['summer', 'north', 'lead', 'expedition', 'dan', 'an', 'to', 'pole', 'during', 'went', 'the'])
      

      【讨论】:

        【解决方案3】:

        试试这个:

        for line in sys.stdin.readline():
            res = set(word.lower() for word in line[:-1].split(" "))
            print res
        

        例子:

        line = "Dan went to the north pole to lead an expedition during summer."
        res = set(word.lower() for word in line[:-1].split(" "))
        print res
        
        set(['north', 'lead', 'expedition', 'dan', 'an', 'to', 'pole', 'during', 'went', 'summer', 'the'])
        

        在 cmets 之后,我编辑:此解决方案保留输入顺序并过滤分隔符

        import re
        from collections import OrderedDict
        line = "Dan went to the north pole to lead an expedition during summer."
        list(OrderedDict.fromkeys(re.findall(r"[\w']+", line)))
        # ['Dan', 'went', 'to', 'the', 'north', 'pole', 'lead', 'an', 'expedition', 'during', 'summer']
        

        【讨论】:

        • 也应该在 .只是为了确保它对 OP 的问题是真实的。
        • 用 line[:-1] 完成 :)
        • 不,不完全是,因为您可能有多个句子。仅仅因为它适用于 OPs 示例并不意味着它适用于野外。
        • 空格不是唯一可以区分我的话,任何标点符号都可以..
        • 请看我的版本,带有任何分隔符和保留顺序
        猜你喜欢
        • 1970-01-01
        • 2011-04-03
        • 2021-12-03
        • 2019-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-05
        相关资源
        最近更新 更多