python将单词转化为数字_在python3中,如何将单词转换成数字(自己的键和值)?...

您将不得不处理标点符号,但您只需将每个单词字母的值求和并对它们进行分组即可使用defaultdict:lines = """am writing a Python script that will take words in a text file and convert them into numbers (my own, not ASCII, so no ord function).

I have assigned each letter to an integer and would like each word to be the sum of its letters' numerical value.

The goal is to group each word with the same numerical value into a dictionary.

I am having great trouble recombining the split words as numbers and adding them together"""

from collections import defaultdict

d = defaultdict(list)

for line in lines.splitlines():

for word in line.split():

d[sum(l_n.get(ch,0) for ch in word)].append(word)

输出:

^{pr2}$

sum(l_n.get(ch,0) for ch in word)获取单词中所有字母的和,我们将其用作键,并将单词附加为值。defaultdict处理重复的键,因此我们以列表中分组的具有相同和的所有单词结束。在

同样,正如John所说,您可以简单地在dict中存储一组小写字母并调用.lowersum(l_n.get(ch,0) for ch in word.lower())

如果要删除所有标点符号,可以使用str.translate:from collections import defaultdict

from string import punctuation

d = defaultdict(list)

for line in lines.splitlines():

for word in line.split():

word = word.translate(None,punctuation)

d[sum(l_n.get(ch,0) for ch in word)].append(word)

这将产生:{1: ['a', 'a', 'a'],

7: ['be'],

9: ['I', 'I'],

14: ['am', 'am'],

15: ['an'],

17: ['each', 'each', 'each'],

19: ['and', 'and', 'and'],

20: ['as'],

21: ['of'],

23: ['in'],

28: ['is'],

29: ['no'],

32: ['file'],

33: ['the', 'The', 'the', 'the'],

34: ['so'],

35: ['to', 'to', 'goal', 'to'],

36: ['have'],

37: ['take', 'ord', 'like'],

38: ['my', 'same'],

39: ['adding'],

41: ['ASCII'],

46: ['them', 'them'],

48: ['its'],

49: ['that', 'not'],

51: ['great'],

52: ['own'],

53: ['sum'],

56: ['will'],

58: ['into', 'into'],

60: ['word', 'word', 'with'],

61: ['value', 'value', 'having'],

69: ['text'],

75: ['would'],

76: ['split'],

77: ['group'],

78: ['assigned', 'integer'],

79: ['words', 'words'],

80: ['letter'],

85: ['script'],

92: ['numbers', 'numbers'],

93: ['trouble'],

96: ['numerical', 'numerical'],

97: ['convert'],

98: ['Python', 'together'],

99: ['letters'],

100: ['writing'],

102: ['function'],

109: ['recombining'],

118: ['dictionary']}

如果不希望出现重复的单词,请使用集合:d = defaultdict(set)

....

d[sum(l_n.get(ch,0) for ch in word)].add(word)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值