[英]iterating through list based on character value in each list element (python)
[英]Replace all lines containing a certain character with elements from a list, iterating through each element for each line in input
好的,所以我有一個輸入文件,其中包含一些我想用不同的行替換的行(使用 python)。 例如,輸入文件中第一次出現的包含 H 的行被另一個文件(稱為 x)的第一行替換,輸入文件中第二次出現的包含 H 的行被替換為x 文件等。 包含 H 的行的出現次數與另一個文件 (x) 中的行數相同。 這是我到目前為止所擁有的:
original = open('PROJECT-pos-1.xyz', 'r')
output = open('output.txt', 'w')
list1 = open('H.txt', 'r')
terms = list1.readlines()
text = original.read()
for term in terms:
text = text.replace('H', term, 1)
output.write(text)
original.close()
output.close()
list1.close()
在此示例中,H.txt 是包含替換列表的文件,POSITION 文件是包含要替換的行的文件。 任何幫助深表感謝。
有兩種明顯的方法可以做到這一點:
方法 1 :將文件 H 的內容作為列表讀取,然后繼續獲取列表H[0]
的第一個元素,同時使用H.pop(0)
減少列表。
方法 2 :類似於方法 1。將文件 H 的內容作為列表讀取,然后有一個計數器i
隨着每次替換而增加,這樣您就可以調用H[i]
。
我更喜歡方法2...
這是一個示例(帶有列表而不是文件):
input = ['Hello', 'World', 'How', "Are", "You"]
terms = ['dog', 'cat', 'mouse']
output = []
print('input:', input)
i = 0
for w in input:
# loop through the input
if w[0]=='H':
output.append(terms[i])
i = i + 1
if i >= len(terms):
# reset counter if not enough terms
i = 0
else:
output.append(w)
print('output:', output)
結果:
input: ['Hello', 'World', 'How', 'Are', 'You']
output: ['dog', 'World', 'cat', 'Are', 'You']
OP 可以將其從列表修改為文件 readlines。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.