簡體   English   中英

Python 收縮函數

[英]Python Contraction Function

(我已經知道有一個庫可以處理收縮並且能夠使用它)

但....

作為一個初學者,我也在嘗試學習如何用 Python 編程,閱讀文本等。在這里我想做的是刪除“”並擴展收縮。 刪除斜線工作得很好。 這是我沒有運氣的宮縮擴大。 請參閱下面的代碼

contractions = {
"ain't" :"am not",
"aren't": "are not",
"can't": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",    
"haven't": "have not",
"he'd": "he would",
"he'd've": "he would have",
"he'll": "he will",
"he'll've": "he will have",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how does",
"i'd": "i would",
"i'd've": "i would have",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it would",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"must've": "must have",
"mustn't": "must not",
"musn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not have",
"she'd": "she would",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so is",
"that'd": "that would",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there would",
"they'd":  "they would",
"they'd've": "they would have",
"they'll": "they will",    
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
" u ": "you",
" ur ": "your",
" n ": " and "
}
print(contractions)

def cont_to_exp(x):
    if type(x) is str:
        x= x.replace('\\','')
        for key in contractions:
            value = contractions[key]
            x= x.replace(key,value)
            return x
        else:
            return x
    x="don't"

    print(cont_to_exp(x))    

感謝任何建議。

在返回之前,您必須讓整個循環運行。

print(contractions)

def cont_to_exp(x):
    if type(x) is str:
        x= x.replace('\\','')
        for key,value in contractions.items():
            x = x.replace(key,value)
        return x
x="don't"
print(cont_to_exp(x)) 

for key in contractions - 一般來說,這不是您使用字典對象的方式。 就個人而言,我會糾正循環中不必要的replace語句,因為這可能會在字符串過長時變得昂貴。

雖然老實說,我也不確定你是否需要一個循環——所以也許是這樣的。

def cont_to_exp(x):
    assert type(x) is str, f"help me, I got a {type(x)}, wanted `str`"
    x= x.replace('\\','')
    return contractions.get(x, x)

x="don't"

print(cont_to_exp(x))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM