![](/img/trans.png)
[英]How can I access specific parts of a string in a txt file with python?
[英]I need to add some string to specific parts of a txt file in python
假設我有一個 .txt 文件,其中包含如下測試:
1
問題舉例?
A) 答案 B) 其他答案 C) 其他答案
2
另一個問題示例?
A) 好的答案 B) 不錯的答案 C) 不好的答案
3
第三個問題舉例?
...還有另外 300 個問題
我有這些問題的正確答案列表,例如: ['B', 'A', 'C', 'A' ... ' D']
(按順序排列)
我想修改文本文件,以便此列表中的每個答案都在其問題的編號旁邊,例如:
1B
問題舉例?
...
2A
另一個問題示例?
...
等等。
我已經嘗試了很多東西,但我真的不能正確地得到它
所以,首先想到的是:
listOfLines = yourInputAsAString.split("\n")
for i in range(len(listOfLines)):
b = i*3;
listOfLines[b] = str(i)+ listOfAnswers[i]
for line in listOfLines:
outputfile.write(line)
這是一種方法,假設答案的順序和數量是正確的:
answers = ['B', 'A', 'C']
with open('answers.txt') as in_file, open('answers2.txt','w') as out_file:
idx = 0
for line in in_file:
if line.strip().isdigit():
out_file.write(line.strip() + answers[idx])
idx += 1
else:
out_file.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.