Python2.7中的字符串替换映射

时间:2013-10-30 16:26:49

标签: python string python-2.7 types

我的文件包含字符串“one”,“two”等所有数字表示。我希望它们被替换为实际的数字1,2,3等。也就是说,我希望将{“0”,“1”,“2”,......,“9”}映射到{“0” ,“1”,......“9”} 我怎么能以pythonic的方式做到这一点?

2 个答案:

答案 0 :(得分:1)

使用关联数组,在Python中称为“字典”:

themap={"one":1, "two":2}   # make a dictionary
themap["one"]    # evaluates to the number 1

这适用于任何类型的数据,因此,根据您的问题,

themap={"one":"1", "two":"2"}
themap["one"]    # evaluates to the string "1"

一次映射大量值:

inputs=["one","two"]   # square brackets, so it's an array
themap={"one":1, "two":2}   # braces, so it's a dictionary
map(lambda x: themap[x], inputs)  # evaluates to [1, 2]

lambda x: themap[x]是一个查找themap项目的功能。 map()调用inputs的每个元素的函数,并将结果作为数组放在一起。 (在Python 2.7.3上测试)

答案 1 :(得分:0)

dict将双向完成这项任务:

st='zero one two three four five six seven eight nine ten'
name2num={s:i for i,s in enumerate(st.split())}
num2name={i:s for i,s in enumerate(st.split())}

print name2num
print num2name
for i, s in enumerate(st.split()):
    print num2name[i], '=>', name2num[s]

打印:

{'seven': 7, 'ten': 10, 'nine': 9, 'six': 6, 'three': 3, 'two': 2, 'four': 4, 'zero': 0, 'five': 5, 'eight': 8, 'one': 1}
{0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'}
zero => 0
one => 1
two => 2
three => 3
four => 4
five => 5
six => 6
seven => 7
eight => 8
nine => 9
ten => 10

您还可以使用课程:

class Nums:
    zero=0
    one=1
    two=2
    three=3
    # etc

print Nums.zero
# 0
print Nums.one     
# 1
print getattr(Nums, 'two')
# 2

或者,使用类枚举的另一种方法:

class Nums2:
    pass

for i, s in enumerate(st.split()):
    setattr(Nums2, s, i)        

for s in st.split():
    print getattr(Nums2,s)  
# prints 0-10...

或者等待Python 3.4以及PEP 435

中描述的Enum类型的实现