我有一个string
,其中包含单词格式的数字(带字符串前缀)。我想将其转换为整数格式的数字字符串(字符串前缀保持原样)。以下是字符串的一些示例数据:
"m.l. one two three four"
"k.f two seven six eight"
"g.h three nine zero four"
我希望他们每个人都转换为:
"ML1234"
"KF2768"
"GH3904"
我环顾四周,但无法找到相关的问题(大多数SO问题都与将数十,数百,数千转换为整数有关。)
我该怎么转换呢?
答案 0 :(得分:3)
一个简单的解决方案:
string = "m.l. one two three four"
text_dict = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six': 6, 'seven':7, 'eight':8, 'nine':9, 'zero':0}
split = string.split()
numerized = [str(text_dict[word]) for word in split[1:]]
prefix = split[0].upper().replace(".","")
print ("".join([prefix] + numerized))
输出:
ML1234
答案 1 :(得分:0)
functools.reduce的解决方案:
from functools import reduce
text = "m.l. one two three four"
rep = [(" zero", "0"), (" one", "1"), (" two", "2"), (" three", "3"),
(" four", "4"), (" five", "5"), (" six", "6"), (" seven", "7"),
(" eight", "8"), (" nine", "9"), (".", "")]
t = reduce(lambda a, kv: a.replace(*kv), rep, text.lower()).upper()
print(t)
输出:
ML1234
答案 2 :(得分:0)
data = "m.l. one two three four"
numbers = {
"one":1,
"two":2,
"three":3,
"four":4,
"five":5,
"six":6,
"seven":7,
"eight":8,
"nine":9,
"zero":0
}
def num_map(str):
return numbers[str]
data = data.split()
# data[0] will be having chars, rest are numbers
tmp = ''.join(data[0].split('.')[:-1])
tmp += ''.join(map(str,map(num_map, data[1:])))
print tmp.upper()
将字符串映射到int,反之亦然
答案 3 :(得分:0)
除了必须使用reduce
函数或名为words2num
的小型库外,您还有很多选择可供选择。
如果您使用的是python 2.x,则可以直接包含reduce
,或者如果您使用的是python 3.x,请使用functools.reduce
。
来自umutto的回答:Python 2.x
text = "m.l. one two three four"
rep = [(" zero", "0"), (" one", "1"), (" two", "2"), (" three", "3"),
(" four", "4"), (" five", "5"), (" six", "6"), (" seven", "7"),
(" eight", "8"), (" nine", "9"), (".", "")]
t = reduce(lambda a, kv: a.replace(*kv), rep, text.lower()).upper()
print t
输出
ML1234
这就够了。如果您想使用库words2num
是一个不错的选择
1,安装words2num
pip install words2num
2,导入'words2num'
from words2num import w2n
3,使用w2n()
函数
string = "m.l. one two three four"
word_str = string.split(" ")
result = ""
for i in word_str:
try:
result += str(w2n(i))
except:
words = i.upper().split(".")
result += "".join(words)
print result
输出
ML1234