CSV-fi中的词汇量大小

2024-03-29 01:21:10 发布

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

我有一个CSV文件,看起来像:

Lorem ipsum dolor sit amet , 12:01
consectetuer adipiscing elit, sed , 12:02

等等。。。在

这是一个相当大的文件(大约10000行) 我想得到所有行文本的总词汇量。也就是说,忽略第二列(时间),将所有内容小写,然后计算不同单词的数量。在

问题: 1) 如何在每行中分隔每个单词 2) 如何将所有内容小写并删除非字母字符。在

到目前为止,我有以下代码:

^{pr2}$

谢谢你的帮助!在


Tags: 文件csv文本内容单词sed小写ipsum
2条回答

你有你需要的东西。缺少的一点是小写转换,只需使用word.lower()即可完成。在

另一件你缺少的事就是分词。您应该为这个任务使用.split(),默认情况下,它会拆分每个空格字符,即空格、制表符等

您将遇到的一个问题是区分文本中的逗号和列分隔逗号。也许不要使用csv阅读器,只需阅读每一行并删除时间,然后将其拆分成单词。在

import re

with open('/Users/file.csv', 'rb') as file:
    for line in file:
        line = re.sub(" , [0-2][0-9]:[0-5][0-9]", "", line)
        line = re.sub("[,|!|.|?|\"]", "", line)
        words = [w.lower() for w in line.split()]
        for word in words:
            ...

如果要删除其他字符,请将它们包含在第二个正则表达式中。如果性能对您很重要,您应该在for循环之前编译两个正则表达式一次。在

pythonscsv模块是一个很好的库,但是经常使用它来完成更简单的任务可能会有点过头。 对我来说,这是一个典型的例子,使用csv模块可能会使事情过于复杂

对我来说

  • 只是在文件中迭代
  • 以逗号分隔每行,并提取第一个拆分
  • 然后在空白处分割剩余部分
  • 将每个单词转换为小写
  • 去掉所有的标点和数字
  • 把结果理解为一个集合

是一种线性的直接方法

使用以下文件内容运行的示例

Lorem Ipsum is simply dummy "text" of the ,0
printing and typesetting; industry. Lorem,1
 Ipsum has been the industry's standard ,2
dummy text ever since the 1500s, when an,3
 unknown printer took a galley of type and,4
 scrambled it to make a type specimen ,5
book. It has survived not only five ,6
centuries, but also the leap into electronic,7
typesetting, remaining essentially unch,8
anged. It was popularised in the 1960s with ,9
the release of Letraset sheets conta,10
ining Lorem Ipsum passages, and more rec,11
ently with desktop publishing software like,12
 !!Aldus PageMaker!! including versions of,13
Lorem Ipsum.,14

^{pr2}$

相关问题 更多 >