如何在python中计算文本文件中的特殊字符?

2024-04-24 01:17:24 发布

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

我想计算一个文本文件中非字母数字字符的数量,这样我就可以将该计数作为我的文本分类功能集中的一个特性。 任何帮助都会大有帮助。在


Tags: 文本功能数量字母分类数字特性字符
3条回答

您可以简单地遍历该文件并使用^{}方法来计算非字母数字字符的数量。在

比如说:

count_special = 0
with open(filename,mode='r') as f:
    for line in f:
        count_special += sum(not x.isalnum() for x in line)
print(count_special)

所以在循环之后,count_special包含非字母数字字符的总数。在

通过一次解析一行,该方法通常能够处理大型文本文件,因为它不必首先将整个文件加载到内存中。在

此函数将返回文件中非字母数字字符的数目:

def count_non_alphanumeric(filename):
    with open(filename, "r") as f: #open the file as f
        nonalpha_count=0           # this is the running count of alphanumeric chars
        for line in f: #for each line in the file...
            for ch in line:  #for each character in the line...
                if not ch.isalnum():  # check to see if the character is alphanumeric
                    nonalpha_count+=1
    return nonalpha_count

你可以用这个方法。必须将特殊字符列表定义为regex

import re
x = re.compile("[^A-Za-z0-9]") 
# also you can use "[^\w]" or "[\W]" patterns

并以re.findall的长度计算特殊字符数:

^{pr2}$

相关问题 更多 >