你知道吗测试.txt包含以下句子(如果一只土拨鼠可以的话,一只土拨鼠需要多少木头 (查克·伍德)
这个程序应该读取给定文本文件中的所有单词(直到eof) 并打印出每个单词的计数。这个词应该是 不区分大小写(所有大写),标点符号应为 移除,输出应按 频率。你知道吗
不过,我遇到了一个简单的问题,那就是数台词,而不是字数,帮帮一个兄弟。你知道吗
Make a translation table for getting rid of non-word characters
dropChars = "!@#$%ˆ& ()_+-={}[]|\\:;\"’<>,.?/1234567890"
dropDict = dict([(c, '') for c in dropChars])
dropTable = str.maketrans(dropDict)
Read a file and build the table.
f = open("Test.txt")
testList=list()
lineNum = 0
table = {} # dictionary: words -> set of line numbers
for line in f:
testList.append(line)
for line in testList :
lineNum += 1
words = line.upper().translate(dropTable).split()
for word in words:
if word in table:
table[word].add(lineNum)
else:
table[word] = {lineNum}
f.close()
Print the table
for word in sorted(table.keys()):
print(word, end = ": ")
for lineNum in sorted(table[word]):
print(lineNum, end = " ")
print()
首先,你必须决定你对一个词的定义是什么。
定义1:单词是由空格分隔的字符序列。所以“you've”是一个单词,“o'clock”也是一个单词。你知道吗
定义2:一个词是“一个独特的有意义的元素的讲话或写作”。在这种情况下,“you've”是两个不同的单词(you+have),“o'clock”是一个单词。你知道吗
因此,如果您运行:
然后您将得到以下csv文件:
注意“ve”(来自“you've”)是一个独立的词。你知道吗
但是如果在标记化中将semantic=True改为semantic=False
然后你会得到:
然而,在我们的频率表中将“have”写成“ve”并不是很人性化。我们可以利用收缩映射来解决这个问题。你知道吗
那么问题就解决了。你知道吗
f=打开('测试.txt')
cnt=0 对于f.read().split()中的单词: 打印(word) cnt+=1 打印cnt
这也许对你有帮助,兄弟…虽然我也是python的新手。你知道吗
此代码:
印刷品:
我想知道代码是不是太短了?=)
相关问题 更多 >
编程相关推荐