python - 计算每个标点符号
问题描述
我有一个包含大量数据的 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 ....
我感谢任何帮助,谢谢。
解决方案
这是使用正则表达式的一种方法。
前任:
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
推荐阅读
- java - 变量前面的减号是否使第一个变量为负?
- javascript - 在对象的对象内部搜索并替换值
- css - 当属性值更新时,React 子组件 css 停止工作
- ruby - Ruby 中所有魔法指令的列表
- php - PHP 启动:composer 安装/更新后打开 index.php 失败
- r - 修复丢失的数据 - 如何将表格转换为与 KalmanRun 一起使用的 ts 对象?
- vba - Append a variant of strings to an empty variant array
- javascript - Can someone explain how this finds the max number?
- python - Merge/Join pandas command to mark all shared instances of a column in df with that of a column of other df
- facebook - 我需要更多信息:应该明确提供“fb:app_id”属性