使用正则表达式计算字符串中的单词

时间:2019-12-17 01:15:02

标签: python regex

在过滤掉某些字符(例如“!”#$%&'()*,-。/:;?@ [] _“)之后,我试图计算长字符串中每个单词的出现次数而我使用正则表达式来做到这一点。

并重新格式化输出以使用制表符分隔

所以我面临两个问题:

1-在函数中使用return只能产生第一行,但是当用print函数代替时,它可以正常工作。但是我担心使用打印而不是退货。

2-在TMC服务器上,它返回一个我不理解的错误。

错误:-

Failed: test.test_word_frequencies.WordFrequencies.test_first
        'NoneType' object is not subscriptable

Test results: 1/2 tests passed
 50%[????????????????????????????????????????????????????????????????]

到目前为止,这是我的进步:-

def word_frequencies(file):
    import re
    from collections import Counter

    counts = []
    inputfile = open(file,"r")
    textfile = inputfile.read()
    pattern = re.compile(r'([\!\"\#\$\%\&\'\(\)\*\,\-\\.\\\/\:\;\?\@\[\]\_])')
    file_clean = re.sub(pattern,"",textfile)
    words = file_clean.split()
    for word in words:
        counts.append(Counter(words)[f'{word}'])
    for word,count in zip(words,counts):
        print(f"{word}\t{count}")

我不确定在最后一个for循环中使用return函数是否明智,因为它会返回:-

'The\t64'

而不是:-

The 64
Project 83
Gutenberg   27
EBook   3
of  303
Alice   166
etc...

我不确定此错误来自何处。

1 个答案:

答案 0 :(得分:0)

Return语句返回您要追加到列表中的内容。

在您的示例中,

for word,count in zip(words,counts): 
    result.append(f"{word}\t{count}")
print(result)

这是打印语句,您要打印列表而不是元素本身。请尝试以下

for data in result:
    print(data)