gpt4 book ai didi

python - 计算 .txt 文件中值的连续出现次数

转载 作者:行者123 更新时间:2023-11-28 16:26:00 25 4
gpt4 key购买 nike

我有一个 .txt 文件,其中有两个单词在不同的行中重复。

这是一个例子。 (实际长约8万行)

ANS
ANS
ANS
AUT
AUT
AUT
AUT
ANS
ANS
ANS
ANS
ANS

我正在尝试开发一些 Python 代码来计算连续行数并返回它们重复的次数。所以对于这个例子,我想将 [3,4,5] 返回到另一个 .txt 文件

word="100011010"
count=1
length=""

for i in range(1, len(word)):

if word[i-1] == word[i]:
count += 1

else:
length += word[i-1]+" repeats "+str(count)+", "
count=1

length += ("and "+word[i]+" repeats "+str(count))
print (length)

这个概念类似于上面的字符串代码。有没有办法用列表来做到这一点?

最佳答案

你可以这样阅读整个文件:

content = []
with open('/path/to/file.txt', 'r') as file
content = file.readlines()
#Maybe you want to strip the lines
#content = [line.strip() for line in file.readlines()]

这里有一个包含文件所有行的列表

def count_consecutive_lines(lines):
counter = 1
output = ''
for index in range(1, len(lines)):
if lines[index] != lines[index-1]:
output += '{} repeats {} times.\n'.format(lines[index], counter)
counter = 1
counter += 1
return output

这样称呼

print(count_consecutive_lines(content))

关于python - 计算 .txt 文件中值的连续出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com