【问题标题】:Remove special char out of a word从单词中删除特殊字符
【发布时间】:2018-11-29 06:25:59
【问题描述】:

我正在尝试计算长字符串中的单词频率。我已使用 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!'))

结果是:

['H', 'e', 'l', 'l', 'o', '!']

你好!

我想知道为什么“!”没有换成“”?我确实在 line 上输入了一个测试代码,它显示了比较有效。

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

【问题讨论】:

  • 只是改变 i 有什么用,这只是一个循环迭代器?您需要替换字符串的字母。
  • 嗨奥斯汀,我想到了你提到的问题,但是当我尝试将 i 打印为循环通过 s 时,它确实打印出“H”,“e”,......每次循环运行。我在这里代表什么?它不能是数字索引(因为我打印出来进行测试)。是字符串索引还是列表的值本身?
  • i 是在每次迭代中一次取一个字符串的字母。当您执行i = "" 时,您只是在更改该变量。原始字符串保持不变。
  • 谢谢奥斯汀。对那个变量 i 感到困惑。你现在对我说清楚。

标签: python string replace char


【解决方案1】:

使用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

【讨论】:

  • 我需要一个函数,因为我将遍历一个包含许多单词的列表并清理它们中的每一个。你的工作完美,谢谢。列表 - 理解很高兴知道。
【解决方案2】:

解决起来比较容易:

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

print(clean_word('Hello!'))

您的代码错误:在您编写的代码中i="",它更改了变量i 的值,而不是原始字符串。

【讨论】:

  • 感谢您对变量 i 的澄清。
【解决方案3】:
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

【讨论】:

    【解决方案4】:

    你应该使用列表推导,更快更简洁:

    replace_list = [':','.',',','!','?']
    
    word = "H:e.l,l!o?"
    
    print ''.join([c for c in word if c not in replace_list]) #OUTPUTS: Hello
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 2016-01-23
      相关资源
      最近更新 更多