Py学习  »  Python

如果python不区分大小写,如何用特定模式替换给定句子中的单词?

Mazil_tov998 • 3 年前 • 1484 次点击  

我被判刑了 我的球队是锦标赛中最好的球队。 作为创建函数的测试用例

def case_insensitivity(sentence):
    return new_sentence

它检查给定句子中不区分大小写的单词,并将不区分大小写的单词替换为 XXX_ .

print(case_insensitivity('My team is the BeST team at the tournament'))
result
'My team is the XXX_ team at the tournament'

最好的方法是什么? casefold()

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131472
文章 [ 2 ]  |  最新文章 3 年前
ThiefMaster sipi09
Reply   •   1 楼
ThiefMaster sipi09    3 年前

这是我的解决方案(希望我能很好地理解你的问题):

  1. 你把句子分成了几个词。

  2. 你把所有的单词循环一遍

  3. 你从每个单词的第二个字母开始循环单词的字母。

  4. 检查是否有大写字母

  5. 如果你找到大写字母,你给have_to_replace变量加1。

  6. 你来替换

    txt = 'My team is the BeST team at the tournament'
    x = txt.split()
    
    for w in x:
        have_to_replace = False
        for l in w[1:]:
            if l != l.casefold():
                have_to_replace = True
        if have_to_replace:
            txt = txt.replace(w, 'XXX_', 1)
    print(txt)
    

由于某些原因,前三行(以及最后一行)的代码阻塞无法正常工作。抱歉。

Tim Biegeleisen
Reply   •   2 楼
Tim Biegeleisen    3 年前

假设我们将目标词定义为在第一个字符之外同时包含小写和大写字母,我们可以尝试使用 re.sub 对于正则表达式选项:

def case_insensitivity(sentence):
    return re.sub(r'\w+(?:[A-Z]\w*[a-z]|[a-z]\w*[A-Z])\w*', 'XXX_', sentence)

print(case_insensitivity('My team is the BeST team at the tournament'))

这张照片是:

My team is the XXX_ team at the tournament