将整个文本处理成一行一个单词的形式

path = r'h:\kill a bird.txt'
path_over = r'h:\kill a bird new.txt'

# read all article and every_line put into list
max_list_1 = []
with open(path, 'r') as f:
    lines = f.readlines()

# process every_line : split ' '  convert signal word
for line in lines:
    line_1 = line.split(' ')
    for lin_word_1 in line_1:
        max_list_1.append(lin_word_1 + '\n')

temp_list = []
for lin_word_2 in max_list_1:
    if lin_word_2 != '\n':
        temp_list.append(lin_word_2)

max_list_2 = []
for lin_word_3 in temp_list:
    lin = lin_word_3.replace(',', '').replace('.', '').replace('\n{2,}', '\n').replace('(', '').replace(')', '').replace('!', ''). \
                    replace('\s+', '').replace('`', '').replace("'", '').replace(';', '').replace('-', '').replace('\xa1+', '')
    max_list_2.append(lin)

max_list_3 = []
for lin_word_3 in max_list_2:
    if lin_word_3 == '\n\n':
        continue
    max_list_3.append(lin_word_3)

with open(path_over, 'w') as f_over:
    f_over.writelines(max_list_3)

统计一行文本中单词个数数组通常是指将一段连续的文字拆分单个单词,并计算每个单词出现的次数,然后形一个数组形式的结果。这个过程涉及到自然语言处理(NLP)中的基本步骤,包括分词、去除标点符号和停用词等。 以下是一个简单的步骤概述: 1. **文本预处理**:将字符串转换为小写,以便不区分大小写;去除多余的空白字符(如换行符或制表符)。 2. **分词**:根据语言规则(例如英文空格分隔或使用正则表达式),将文本分割单词列表。 3. **清理词汇**:移除标点符号、数字和其他非字母字符,可能还需要排除一些常见的停用词(如“的”、“是”等在大多数上下文中没有太多含义的词语)。 4. **计数**:遍历单词列表,使用哈希表(Python中的`collections.Counter`或字典)存储每个单词及其出现次数。 5. **数组表示**:最后,将统计结果转化为数组形式,元素为单词,值为对应的频率。 以下是一个简单的Python示例: ```python import re from collections import Counter def count_words(text): # 去除标点符号和转换为小写 text = re.sub(r'[^\w\s]', '', text.lower()) # 分词并计数 words = text.split() word_counts = Counter(words) # 返回单词计数组 return list(word_counts.items()) # 示例用法 text = "这是一段示例文本,包含多个单词,重复的单词会被计数。" word_array = count_words(text) print(word_array) # 输出:[('这', 1), ('是', 1), ('一段', 1), ('示例', 1), ('文本', 1), ...] ``` 如果你想要获取的是每个单词出现次数的数组,而不是元组对(单词, 出现次数),可以稍作调整,仅保留计数值部分: ```python word_counts_array = [count for word, count in word_counts] ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值