Python计数不重置?

2024-04-18 08:39:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在my.txt中出现~ | |之后插入一个增量。我有这个工作,但是我想把它分开,所以在每个分号之后,它从1开始。你知道吗

到目前为止,我有以下内容,除了用分号分开外,其他都做了。你知道吗

inputfile = "output2.txt"    
outputfile = "/output3.txt"  
f = open(inputfile, "r")  
words = f.read().split('~||~')  
f.close()  
count = 1   
for i in range(len(words)):  
      if ';' in words [i]:  
        count = 1  
    words[i] += "~||~" + str(count)  
    count = count + 1  
f2 = open(outputfile, "w")  
f2.write("".join(words))  

Tags: intxtclosereadmycountopen增量
2条回答

为什么不先根据分号拆分文件,然后在每个段中计算“~ | | ~”的出现次数。你知道吗

import re

count = 0

with open(inputfile) as f:
    semicolon_separated_chunks = f.read().split(';')
    count = len(re.findall('~||~', semicolon_separated_chunks))

# if file text is 'hello there ~||~ what is that; what ~||~ do you ~|| mean; nevermind ~||~'
# then count = 4

您可以在;上执行初始拆分,然后在~||~上拆分子字符串,而不是像现在这样重置计数器。你必须以另一种方式存储你的单词,因为你不再做words = f.read().split('~||~'),但无论如何,建立一个全新的列表更安全。你知道吗

inputfile = "output2.txt"    
outputfile = "/output3.txt"  
all_words = []
f = open(inputfile, "r")  
lines = f.read().split(';')
f.close()

for line in lines:
  count = 1
  words = line.split('~||~')
  for word in words:
    all_words.append(word + "~||~" + str(count))
    count += 1

f2 = open(outputfile, "w")  
f2.write("".join(all_words))  

看看这对你有用吗。您还可能希望在其中放置一些战略性的换行符,以使输出更具可读性。你知道吗

相关问题 更多 >