【问题标题】:Text replacement doesn't work in special cases文本替换在特殊情况下不起作用
【发布时间】:2019-02-10 21:28:57
【问题描述】:

我有一个单词列表文件,名为 Words.txt,其中包含数百个单词和一些字幕文件 (.srt)。我想浏览所有字幕文件,并在它们中搜索单词列表文件中的所有单词。如果找到一个单词,我想将它的颜色更改为绿色。这是代码:

import fileinput
import os
import re

wordsPath = 'C:/Users/John/Desktop/Subs/Words.txt'
subsPath = 'C:/Users/John/Desktop/Subs/Season1'
wordList = []

wordFile = open(wordsPath, 'r')
for line in wordFile:
    line = line.strip()
    wordList.append(line)

for word in wordList:
    for root, dirs, files in os.walk(subsPath, topdown=False):
        for fileName in files:
            if fileName.endswith(".srt"):
                with open(fileName, 'r') as file :
                    filedata = file.read()
                    filedata = filedata.replace(' '  +word+  ' ', ' ' + '<font color="Green">' +word+'</font>' + ' ')
                with open(fileName, 'w') as file:
                    file.write(filedata)

假设单词“book”在列表中,并且在其中一个字幕文件中找到。只要这个词出现在“这本书太棒了”这样的句子中,我的代码就可以正常工作。但是,当单词像“BOOK”、“Book”这样被提及时,并且当它位于句首或句尾时,代码就会失败。我该如何解决这个问题?

【问题讨论】:

  • for word.lower() in wordList 会将所有单词转换为小写。现在,确保您还将 .srt 文件中的文件数据降低为小写,仅此而已。您还可以根据需要使用upper()title() 或许多其他人。或者尝试捕捉单词islowerisupperistitle
  • 查看re 模块。您可以以更灵活的方式指定单词边界(如\b),并且可以指定不区分大小写的匹配。
  • 请您提供文件开头的单词导致的错误吗?
  • 感谢@Saelyth 和@jasonharper!

标签: python python-3.x search replace


【解决方案1】:

您使用的是str.replace,来自文档:

Return a copy of the string with all occurrences of substring old replaced by new

这里的出现意味着字符串 old 的完全匹配,然后该函数将尝试替换由空格包围的单词,例如 ' book '' BOOK '' Book '' book' 不同。让我们看看几个也不匹配的案例:

" book " == " BOOK "  # False
" book " == " book"  # False
" book " == " Book "  # False
" book " == " bOok " # False
" book " == "   book " # False

另一种方法是使用这样的正则表达式:

import re

words = ["book", "rule"]
sentences = ["This book is amazing", "The not so good book", "OMG what a great BOOK", "One Book to rule them all",
             "Just book."]

patterns = [re.compile(r"\b({})\b".format(word), re.IGNORECASE | re.UNICODE) for word in words]
replacements = ['<font color="Green">' + word + '</font>' for word in words]

for sentence in sentences:

    result = sentence[:]
    for pattern, replacement in zip(patterns, replacements):
        result = pattern.sub(r'<font color="Green">\1</font>', result)
    print(result)

输出

This <font color="Green">book</font> is amazing
The not so good <font color="Green">book</font>
OMG what a great <font color="Green">BOOK</font>
One <font color="Green">Book</font> to <font color="Green">rule</font> them all
Just <font color="Green">book</font>.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多