【问题标题】:Python 3 - How to continuously remove letters from a sentence?Python 3 - 如何从句子中连续删除字母?
【发布时间】:2017-03-13 05:53:20
【问题描述】:
alphabet_dic = ['a','b','c','d','e','f','g','h','i','j','k','l','n','o','p','q','r','s','t','u','v','w','y','z','m']

doc = Document('test3.docx')
firstSen = doc.paragraphs[0].text
print (firstSen)

indexLetters = 0
while indexLetters < len(c_dic):
    d_dic = c_dic[indexLetters]
    indexLetters += 1
    secondSen = firstSen.replace(d_dic,"")    
    print (secondSen)

测试文档包含句子“Hello There”。 我正在尝试创建一个循环,在其中检查字典中是否有大量特定字母,然后慢慢循环并从“Hello There”中删除字母。

想法:

Sentence = Hello There

helloDic = ['h','e','l','o']

Desire Result = Tr

有什么建议或更好的方法吗?

【问题讨论】:

    标签: python python-3.x ms-word


    【解决方案1】:

    一开始会想到多次应用str.replace,但这样做确实是一种效果不佳的方法(Python str.translate VS str.replace

    作为一个不错的选择,您可以修改您的“字典”以创建一个真正的字典,与str.translate 兼容(也添加大写字母)。然后,您只需使用新的 dict 将 str.translate 函数应用于您的字符串:

    Sentence = "Hello There"
    
    helloDic = ['h','e','l','o']
    
    rep_dic = {ord(k):None for k in helloDic + [x.upper() for x in helloDic]}
    
    print(Sentence.translate(rep_dic))
    

    结果:

     Tr
    

    (保留空格)

    【讨论】:

    • 你不能使用translate方法中提供的deletechars参数吗? S.translate(table [,deletechars]) -&gt; string
    • deletechars 仅适用于 python 2。在 python 3 中,您必须将您的字符映射到None。问题被标记为“python 3”
    【解决方案2】:

    简单的解决方案

    sentence = 'Hello There'
    
    hello_dic = ['h','e','l','o']
    
    r = [s for s in sentence if s.lower() not in hello_dic]
    
    print ''.join(r)
    

    输出

    ' Tr'
    

    【讨论】:

    • 可以简化为s for s in sentence if s.lower() not in hello_dic,因为hello_dic 只包含小写字母。
    • 轮到我建议您使用set 而不是list。不过,对于 4 个字母来说,这没什么大不了的。
    猜你喜欢
    • 2016-09-02
    • 1970-01-01
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多