首页 > 解决方案 > 计算每个标点符号

问题描述

我有一个包含大量数据的 CSV 文件,我想计算每个标点符号的数量。

现在我只知道如何计算文本的整个标点符号,但不是每个都分开。

我想将每行中每个标点符号的编号保存在 CSV 文件中。

以下是我尝试获取每个标点符号的数量,但出现了类似re.error: nothing to repeat at position 0'.

news=pd.read_csv("cluesnew.csv")
news['?']= news.string_column.str.count('?')
news['[']= news.string_column.str.count('[')
news[']']= news.string_column.str.count(']')
news['!']= news.string_column.str.count('!')
news[';']= news.string_column.str.count(';')
news['{']= news.string_column.str.count('{')
news['}']= news.string_column.str.count('}')
news['/']= news.string_column.str.count('/')
news['-']= news.string_column.str.count('-')
news['_']= news.string_column.str.count('_')
news[',']= news.string_column.str.count(',')
news['.']= news.string_column.str.count('.')
news[':']= news.string_column.str.count(':')
news['`']= news.string_column.str.count('`')
news['...']= news.string_column.str.count('...')
news.to_csv("cluesnew.csv")

线索new.csv的一些例子

ID string_column
1  In 2017 alone, death due to diabetes was recorded at 10.1 per cent.
2  12.4 per cent of the country's citizens have diabetes. 

生成的数据框的一个示例是:

string_column                                                         . , [ ] ! ` { ....
In 2017 alone, death due to diabetes was recorded at 10.1 per cent.   1 1 0 0 0 0 0 ....
12.4 per cent of the country's citizens have diabetes.                1 0 0 0 0 1 0 ....

我感谢任何帮助,谢谢。

标签: pythonpandascsv

解决方案


这是使用正则表达式的一种方法。

前任:

import re 
import string

df = pd.DataFrame({'string_column': ['In 2017 alone, death due to diabetes was recorded at 10.1 per cent.', "12.4 per cent of the country's citizens have diabetes."]})
for i in string.punctuation:
    if i == '.':
        df[i] = df['string_column'].str.count(r"{}(?![0-9])".format(re.escape(i)))
    else:
        df[i] = df['string_column'].str.count(re.escape(i))
print(df['.'])
print(df[','])

输出:

0    1
1    1
Name: ., dtype: int64
0    1
1    0
Name: ,, dtype: int64

推荐阅读