【问题标题】:Python strings :Punctuation fix pleasePython字符串:请修复标点符号
【发布时间】:2018-05-07 01:05:13
【问题描述】:

无论标点符号如何,程序都能正确识别单词。我无法将其集成到 spam_indicator(text) 中。

def spam_indicator(文本):

text=text.split()
w=0
s=0
words=[]

for char in string.punctuation:
    text = text.replace(char, '')
return word

for word in text:
    if word.lower() not in words:
        words.append(word.lower())
        w=w+1
    if word.lower() in SPAM_WORDS:
        s=s+1
return float("{:.2f}".format(s/w))

enter image description here


第二个块是错误的。我正在尝试删除标点符号以运行该功能。

【问题讨论】:

    标签: python string replace punctuation


    【解决方案1】:

    尝试先删除标点符号,然后将文本拆分为单词。

    def spam_indicator(text):
        for char in string.punctuation:
            text = text.replace(char, ' ')    # N.B. replace with ' ', not ''
    
        text = text.split()
        w = 0
        s = 0
        words = []
    
        for word in text:
            if word.lower() not in words:
                words.append(word.lower())
                w=w+1
            if word.lower() in SPAM_WORDS:
                s=s+1
    
        return float("{:.2f}".format(s/w))
    

    可以对您的代码进行许多改进。

    • 使用words 的集合而不是列表。由于集合不能包含重复项,因此您无需在将其添加到集合之前检查您是否已经看过该词。
    • 使用str.translate() 删除标点符号。您想用空格替换标点符号,以便split() 将文本拆分为单词。
    • 使用round() 而不是先转换为字符串再转换为浮点数。

    这是一个例子:

    import string
    
    def spam_indicator(text):
        trans_table = {ord(c): ' ' for c in string.punctuation}
        text = text.translate(trans_table).lower()
    
        text = text.split()
        word_count = 0
        spam_count = 0
        words = set()
    
        for word in text:
            if word not in SPAM_WORDS:
                words.add(word)
                word_count += 1
            else:
                spam_count += 1
    
        return round(spam_count / word_count, 2)
    

    如果没有非垃圾邮件,请注意不要除以 0。无论如何,我不确定您想要什么作为垃圾邮件指标值。也许应该是垃圾邮件词的数量除以总词数(垃圾邮件和非垃圾邮件),使其值介于 0 和 1 之间?

    【讨论】:

      猜你喜欢
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2012-06-04
      • 2015-07-07
      • 2012-01-22
      相关资源
      最近更新 更多