2013-10-30 12 views
-2

我有所有數字表示字符串「一」,「二」等文件。我希望他們被替換爲實際的數字1,2,3等。也就是說,我想{「零」,「一」,「兩」,...,「九」}映射到{「0」 ,「1」,...「9」} 我如何以pythonic的方式做到這一點?在Python2.7中的字符串替換的地圖

+0

同類不清楚它是什麼,你要尋找的, –

+0

描述枚舉類型的實現是的,我想我應該已經比較清晰。我有一個帶有一般文本內容的文本文件。在文字之間,在任意的地方都有字形數字。這些以「one」,「two」等詞語形式的數字必須改爲「1」,「2」等。 – Kamalakshi

回答

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]是查找物品01的功能。 map()調用函數爲inputs的每個元素並將結果放在一起作爲數組。 (關於Python 2.7.3測試)

+0

如果你打算使用'map',那麼'lambda'不是必需的 - 考慮'dict'已有的方法...如果發生'KeyError',考慮'map(themap.get,inputs)'默認爲'None'或'map(themap .__ getitem__,inputs)'' 。 (但使用神奇的方法不是非常友好的...) –

+0

感謝您的答案。我已經接受了這個答案,因爲我可以將其修改爲符合我的要求。但我想我在前面陳述我的問題時並不清楚。我已經更新了它。 – Kamalakshi

+0

@Kama,[this](http://stackoverflow.com/questions/1919096)問題涉及在給定的文本塊中替換不同的字符串(如「one」,「two」,...)。看看您更新的問題,我認爲這裏描述的一些技術可能對您有所幫助。 – cxw

0

的字典會做這個工作是雙向的:

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