【问题标题】:Python altering list item in iterationPython在迭代中改变列表项
【发布时间】:2016-10-12 01:45:55
【问题描述】:

我试图让这个 python 代码摆脱与单词相关的标点符号并计算唯一单词。出于某种原因,它仍然计算“你好”。和“你好”。非常感激任何的帮助。

def word_distribution(words):
            word_dict = {}
            words = words.lower()
            words = words.split()
            for word in words:
                if ord('a') <= ord(word[-1]) <= ord('z'):
                    pass
                elif ord('A') <= ord(word[-1]) <= ord('Z'):
                    pass
                else: 
                    word[:-1]
            word_dict = {word:words.count(word)+1 for word in set(words)}
            return(word_dict)

【问题讨论】:

标签: python


【解决方案1】:

当然有更好的方法来实现你想要做的事情,但这个答案修复了你的代码。

字符串是不可变的,列表是可变的。您的代码中没有任何地方在修改列表。并且words[-1] 不会产生任何影响,因为您没有重新分配它并且字符串是不可变的

def word_distribution(words):
        word_dict = {}
        words = words.lower()
        words = words.split()
        for word in words:
            index = words.index(word)
            if ord('a') <= ord(word[-1]) <= ord('z'):
                pass
            elif ord('A') <= ord(word[-1]) <= ord('Z'):
                pass
            else: 
                word = word[:-1]
                words[index] = word 

        word_dict = {word:words.count(word) for word in set(words)}
        return(word_dict)

【讨论】:

  • 谢谢 saurabh,成功了!我没有索引。非常感谢大家的帮助!
  • @BRose 如果它对你有用,那么可以接受这个作为答案:)
【解决方案2】:

你把它弄得太复杂了,正如 Sohier Dane 在 cmets 中提到的那样,你可以利用其他帖子来删除标点符号并将脚本简化为:

import string
def word_distribution(words):
    words = words.translate(None, string.punctuation).lower()
    d = {}
    for w in words.split():
        if w not in d.keys():
            d[w] = 1
        else:
            d[w] += 1   
    return d

结果:

>>> x='Hello My Name Is hello.'
>>> print word_distribution(x)  
>>> {'is': 1, 'my': 1, 'hello': 2, 'name': 1}

【讨论】:

    【解决方案3】:

    我不知道你为什么要在计数中加 1。

    def word_distribution(words):
            word_dict = {}
            words = words.lower().split()
            for word in words:
                if ord('a') <= ord(word[-1]) <= ord('z'):
                    pass
                elif ord('A') <= ord(word[-1]) <= ord('Z'):
                    pass
            word_dict = {word:words.count(word) for word in set(words)}
            return(word_dict)
    

    {'hello': 2, 'my': 1, 'name': 1, 'is': 1}

    编辑:

    正如 brianpck 指出的那样:

    def word_distribution(words):
            word_dict = {}
            words = words.lower().split()
            word_dict = {word:words.count(word) for word in set(words)}
            return(word_dict)
    

    也会给出相同的结果。

    【讨论】:

    • 你为什么要做一个for 循环并为每个分支传递?此外,这不会正确处理标点符号this != this.
    • 我只是发布了他们的代码,修改了他们正在寻找的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 2018-10-12
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多