数字计算函数 - 根据数值处理文本
我正在处理一段文本,也就是《圣经》,我想根据一个字典提取出每个单词中字母的数字值:
def gematria(book):
dict = {
'a':1, 'b':2, 'c':3, 'd':4, 'e':5,
'f':80, 'g':3, 'h':8,'i':10, 'j':10,
'k':20, 'l':30, 'm':40, 'n':50, 'o':70,
'p':80, 'q':100,'r':200, 's':300,
't':400, 'u':6, 'v':6, 'w':800, 'x':60,
'y':10, 'z':7
}
我使用了Nltk模块,得到了:
raw = nltk.corpus.gutenberg.raw(book)
tokens = nltk.word_tokenize(raw)
words_and_numbers = [w.lower() for w in tokens]
words = [w for w in words_and_numbers if re.search('[^0-9:0-9]', w)]
vocab = sorted(set(words))
nested = [list(w) for w in vocab]
我最终得到了每个单词字母的字符串列表,比如说 [['h', 'o', 'l', 'y'],['b', 'i', 'b', 'l', 'e']...]
为了处理每个单词并得到它们的数字值,我使用了以下的列表推导式,并结合 sum()
函数,这样可以工作:
word_value_1 = [dict[letter] for letter in nested[0]]
sum(word_value_1)
word_value_2 = [dict[letter] for letter in nested[1]]
sum(word_value_2)
(...)
问题是:我该如何写一个单独的列表推导式,或者一个循环,来返回一本书中所有单词的数字值,并把它们放在一个大列表里呢?
1 个回答
0
print [sum([dict[letter] for letter in word]) for word in nested]
假设有一个叫做 nested
的变量,它的内容是一个包含两个小列表的大列表,具体内容是 nested = [['h', 'o', 'l', 'y'],['b', 'i', 'b', 'l', 'e']]
。这个大列表里有两个小列表,第一个小列表是字母 'h', 'o', 'l', 'y',第二个小列表是字母 'b', 'i', 'b', 'l', 'e'。
输出结果
[118, 49]