簡體   English   中英

從單詞中刪除特殊字符

[英]Remove special char out of a word

我正在嘗試計算長字符串中的單詞頻率。 我已經使用string.split()方法將字符串拆分為單詞列表,並在拆分長字符串之前通過應用string.lower()刪除了區分大小寫的字符。 我想刪除一些特殊字符,例如“!”,“:”,“。”。 因為這些字符會弄亂字數。 以下是我編寫的函數,但似乎無法正常工作

def clean_word(word):
    replace_list = [':','.',',','!','?']
    s = list(word)
    for i in s:
        for j in replace_list:
            if i == j:
                i=""
print(s) # to see s before it being joined           
word =''.join(s)
return word
print(clean_word('Hello!'))

結果是:

['你好', '!']

你好!

我想知道為什么 ”!” 還沒有被替換為“”? 我確實在行中輸入了測試代碼,它顯示了比較的工作原理。

   if i == j:
       print('Checked')

使用enumerate

def clean_word(word):
    replace_list = [':','.',',','!','?']
    s = list(word)
    for i, x in enumerate(s):
        if x in replace_list:
            s[i] = ""     
    word = ''.join(s)
    return word

print(clean_word('Hello!'))

# Hello

如果您對列表理解感興趣:

word = 'Hello!'
replace_list = [':','.',',','!','?']

print(''.join([x for x in word if x not in replace_list]))
# Hello

可以更輕松地解決它:

def clean_word(word):
    replace_list = [':','.',',','!','?']
    for i in replace_list:
        word = word.replace(i,"")
    return word

print(clean_word('Hello!'))

代碼錯誤:在代碼中,您正在編寫i="" ,它會更改變量i的值,而不是原始字符串。

def clean_word(word):
    replace_list = [':','.',',','!','?']
    new_word = ''
    for x in word:
        if x not in replace_list:
            new_word += x     
    return new_word
print(clean_word('Hello!'))

產量

Hello

您應該使用列表理解,更快更干凈:

replace_list = [':','.',',','!','?']

word = "H:e.l,l!o?"

print ''.join([c for c in word if c not in replace_list]) #OUTPUTS: Hello

暫無
暫無

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

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