我的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
感谢您的帮助!
答案 0 :(得分: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 :(得分:1)
你几乎拥有你需要的东西。一个缺失点是小写转换,可以使用word.lower()
完成。
你缺少的另一件事就是分裂成文字。您应该使用.split()
执行此任务,默认情况下会在每个空白字符(即空格,制表符等)上进行拆分。
您将遇到的一个问题是区分文本中的逗号和列分隔逗号。也许不要使用csv-reader,只需阅读每一行并删除时间,然后将其拆分为单词。
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
循环之前编译两个正则表达式。