CSV文件中的词汇量

0 投票
2 回答
2255 浏览
提问于 2025-04-17 13:18

我有一个CSV文件,内容大概是这样的:

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

等等...

这个文件挺大的,大约有10,000行。我想要计算一下所有文本行的总词汇量。也就是说,忽略第二列(时间),把所有文字都变成小写,然后统计不同的单词数量。

遇到的问题有: 1) 如何把每一行中的单词分开 2) 如何把所有文字变成小写,并去掉非字母的字符。

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

import csv
with open('/Users/file.csv', 'rb') as file:
    vocabulary = []
    i = 0
    reader = csv.reader(file, delimiter=',')
    for row in reader:
        for word in row:
            if row in vocabulary:
                break
            else:
                vocabulary.append(word)
                i = i +1
print i

谢谢你的帮助!

2 个回答

3

Python的csv模块是一个很棒的库,但有时候用它来处理简单的任务可能会显得有些复杂。在我看来,这个例子就是一个经典的案例,使用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

>>> from string import digits, punctuation
>>> remove_set = digits + punctuation
>>> with open("test.csv") as fin:
    words = {word.lower().strip(remove_set) for line in fin
         for word in line.rsplit(",",1)[0].split()}


>>> words
set(['and', 'pagemaker', 'passages', 'sheets', 'galley', 'text', 'is', 'in', 'it', 'anged', 'an', 'simply', 'type', 'electronic', 'was', 'publishing', 'also', 'unknown', 'make', 'since', 'when', 'scrambled', 'been', 'desktop', 'to', 'only', 'book', 'typesetting', 'rec', "industry's", 'has', 'ever', 'into', 'more', 'printer', 'centuries', 'dummy', 'with', 'specimen', 'took', 'but', 'standard', 'five', 'survived', 'leap', 'not', 'lorem', 'a', 'ipsum', 'essentially', 'unch', 'conta', 'like', 'ining', 'versions', 'of', 'industry', 'ently', 'remaining', 's', 'printing', 'letraset', 'popularised', 'release', 'including', 'the', 'aldus', 'software'])
1

你已经有了大部分需要的东西。唯一缺少的就是把字母转换成小写,这个可以简单地用 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 循环之前先编译两个正则表达式。

撰写回答