[英]python 3 - search and replace text file -
我正在使用腳本來搜索和替換逗號分隔的文本文件上的字符串。
將“可用”替換為“不可用”可以很好地工作。
updateBook = updateBook.replace("available", "not-available")
但是,如果字符串包含單引號和/或逗號之類的字符,則失敗。
舉個例子:
替換: “可用”,“ 6ba8c817-d72d-4593-8914-7a40d733b6db”,“免費\\ n”
帶有: '不可用','6ba8c817-d72d-4593-8914-7a40d733b6db','jorge'
我嘗試使用轉義引號和逗號失敗。
updateBook = updateBook.replace("\'available\'\, \'6ba8c817-d72d-4593-8914-7a40d733b6db\'\, \'free",
"\'not-available\'\, \'6ba8c817-d72d-4593-8914-7a40d733b6db\'\, \'jorge")
下面是代碼
# Read in the file
updateBook = None
with open('books.txt', 'r') as f:
updateBook = f.read()
# Replace the target string
updateBook = updateBook.replace("'available', '6ba8c817-d72d-4593-8914-7a40d733b6db', 'free\n'",
"'not-available', '6ba8c817-d72d-4593-8914-7a40d733b6db', 'jorge'")
# Write changes to the file.
with open('books.txt', 'w') as f:
f.write(updateBook)
如果可以的話,請立即讓我們。 謝謝
正則表達式可能會在這里為您提供幫助。 這取決於您需要更換的通用程度。
import re
def repl(match):
d = match.groupdict()
d.update('one': 'non-available', 'two': '6ba8c817-d72d-4593-8914-7a40d733b6db', 'three': 'jorge')
s = '{preone}{one}{pretwo}{two}{prethree}{three}{postthree}'.format(**d)
original_string = 'available...'
escaped_values = map(re.escape, ['available', '6ba8c817-d72d-4593-8914-7a40d733b6db', 'free'])
regex_string = r'^(?P<preone>[\'\"])(?P<one>{0})(?P<pretwo>[\'\"],\s*[\'\"])(?P<two>{1})(?P<prethree>[\'\"],\s*[\'\"])(?P<three>{2})(?P<postthree>[\'\"])$'.format(*escaped_values)
replaced_string re.sub(regex_string, repl, original_string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.