当忽略空行时,如何计算列中的字数

2024-03-28 21:30:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我的文本文件中有以下列表:

香蕉

气球

绿色的 巨人

<如何创建一个计算单词的字典,忽略空行

到目前为止,我的代码是:

def make_dictionary(filename):
    text = open(filename,'r').read()
    wordfreq = {}
    for word in text.strip().split('\n'):
        wordfreq[word] = wordfreq.get(word, 0) +1
return wordfreq
<>这将返回我需要的计数,除了它给我一个空行的计数为“:”7,我不需要。因为绿色巨人这个双字,我不能和()分开。因此,我必须使用“\n”进行拆分


2条回答

在获取当前单词后,但在dict中分配它之前,检查它是否为空,如果为空,则跳过它

for word in text.strip().split('\n'):
    # skip this word if it is blank
    if not word:
        continue
    wordfreq[word] = wordfreq.get(word, 0) +1

This code is relying on the fact that Python considers an empty string, or '' to be a False, while a non-empty string is True

def make_dictionary(filename):
    text = open(filename,'r').read()
    wordfreq = {}
    for word in text.strip().split('\n'):
        for line in text:
            if not line.strip():
                continue
            else:
                wordfreq[word] = wordfreq.get(word, 0) +1
return wordfreq

相关问题 更多 >