Flask python 中的字数统计

word count in python with Flask

我正在使用 HTML 和 Flask 服务器创建页面,在 python 中编写函数以在纯文本文件 (demo.txt) 中搜索单词,我的代码工作正常 return 正确的词。我想统计单词在文本中出现的次数

def getText(self,word):
     try:

       myfile=open("E:\Python_work\demo.txt","r");
        mylist=[];
        text=word;
        for line in myfile:
            if text in line:
                   mylist.append(line);
        return mylist;
        myfile.close();
     except:
        return err;

这对我有用:

def getText(self, word):
    try:
        counter = 0
        myfile=open("D:\demo.txt","r");
        for line in myfile:
            counter += line.count(word)
        myfile.close()
        return counter
    except:
        return err

如果您要计算某个单词出现的次数,为什么函数 return 是一个列表?您确定要 return 出现的次数?

您可以尝试这样的操作:

myfile = open('/path', 'r')
text = word
word_count = 0
for line in myfile:
    if text in line:
        word_count += 1

myfile.close()
return word_count

编辑:上面的代码当然在 try 块中。

旁注:分号在 Python 中是不好的风格。当您使用它们时,解释器将每一行视为两条语句,第二条语句为空白。 Python 的解释器使用空格来知道语句何时结束。

您可以使用字符串的计数方法来获取总计数。下面是计算文本文件中单词数的函数。

def count_words(word_to_be_count):
    with open("E:\Python_work\demo.txt","r") as f:
        content = f.read()
        total_count = content.count(word_to_be_count)
    return total_count

以下是在 Python 中执行此操作的好方法 - 假设函数是 class 定义的一部分:

def getText(self, word):
    with open("D:\demo.txt") as f:
        return f.read().count(word)

这假定您将处理调用方的异常(如果文件不存在)。否则使用 try/except 和 return 合适的失败值:

def getText(self, word):
    try:
        with open("D:\demo.txt") as f:
            return f.read().count(word)
    except IOError:
        return -1