我有一個文本檔案,其中有幾個方括號 [] 表示需要替換的文本部分。我還有一個字串串列,我想用它來替換文本檔案中的文本。我的單詞串列是:
inputs = ["John", "Friday", "Kyle"]
words = ["name", "day", "name"]
當串列中超過 1 個字串相同時會發生什么?
例如:“你好,我的名字是 [name]。明天是 [day]。
我希望文本如下:“你好,我的名字是約翰。明天是星期五。
這就是我想要做的作業
f = open(file_name, 'r')
lib_lines = f.readlines()
for index,line in enumerate(lib_lines):
re.sub(words[index], inputs[index], line)
file_contents = f.read()
print (file_contents)
uj5u.com熱心網友回復:
string.replace("before", "after")
因此,如果您想將字串中的“[name]”替換為“John”,請執行
file_contents.replace("[name]", "John")
如果這些存盤在一個串列中,那么做
neatString = file_contents.replace(f"[{words[0]}]", inputs[0])
如果您想回圈并自動獲取所有單詞:
neatString = file_contents
for i, word in enumerate(words):
neatString = neatString.replace(f"[{words[i]}]", inputs[i])
uj5u.com熱心網友回復:
這是一種方法:
from io import StringIO
inputs = ["John", "Friday"]
words = ["name", "day"]
in_file = StringIO("""
Hello, my name is [name].
Tomorrow will be [day].
""".strip())
# with open(file_contents) as in_file:
file_contents = in_file.read()
for word, repl in zip(words, inputs):
file_contents = file_contents.replace(f'[{word}]', repl)
# write file contents to file-like object
out_file = StringIO()
out_file.write(file_contents)
# read in new contents
out_file.seek(0)
print(out_file.read())
輸出:
Hello, my name is John.
Tomorrow will be Friday.
uj5u.com熱心網友回復:
如前所述string.replace("[name]", "John")會更容易
我建議使用 dict,但也有易于使用的安靜且不需要按順序排列并使用要替換的索引。
dict = {'[name]': 'John', '[day]': 'Friday'}
str = "Hello, my name is [name]. Tomorrow will be [day]."
for key, value in dict.items():
str = str.replace(key, value);
print(str);
# output : Hello, my name is John. Tomorrow will be Friday.
它會通過您提供的字串中的值更改每個鍵,因此如果您多次出現 [name],它將更改所有鍵。
dict = {'[name]': 'John', '[day]': 'Friday'}
str = "Hello, my name is [name]. Tomorrow will be [day]. And my name is still [name]"
for key, value in dict.items():
str = str.replace(key, value);
print(str);
# output : Hello, my name is John. Tomorrow will be Friday. And my name is still John
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478270.html
下一篇:給定串列中數字的平均值
