比较单个文本文件中的行

2024-10-04 01:31:01 发布

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

我有一个文本文件,它由相似的行组成,很少有行与文本文件中的其他行一半相似

Input.txt

I would like to play: Volleyball
I would like to play: Volleyball
I would like to play: TableTennis
I would like to play: Baseball
I do not know how to play: Volleyball
She would like to play: TableTennis
I want to learn how to play: Baseball
They like to play: all the three

我想从输入文件中删除重复的行,如图所示

I would like to play: Volleyball
I would like to play: TableTennis
I would like to play: Baseball
I do not know how to play: Volleyball
She would like to play: TableTennis
I want to learn how to play: Baseball
They like to play: all three

我想从输入文件中删除重复的行,如图所示

I would like to play: Volleyball
I would like to play: TableTennis
I would like to play: Baseball
I do not know how to play: Volleyball
She would like to play: TableTennis
I want to learn how to play: Baseball
They like to play: all three

下一步:

I would like to play
They like to play

输出文件的简要说明 我想参加的声明涵盖了许多不同的运动,所以我想打印出来。他们喜欢玩的最后一行是另一种情况,所以我也想打印这一行。(我们如何将这些结果写入.csv格式,并在不同列中打印涵盖最多运动项目以及所有独特运动项目的报表)

注: 我不想打印 我不知道怎么打:排球 她想打乒乓球 我想学打棒球

因为已经报道了三项运动

我对我们如何在同一个文本文件中比较一行和另一行感到困惑。任何帮助都将不胜感激。多谢各位


Tags: toplaynotdolikehowknow文本文件
2条回答

这很简单,在“.py”文件中这样做:

"""Simple Solution To Your Problem!"""

# Opening The Input File- `input.txt`
f = open('input.txt', encoding='utf-8', mode='w+')
new_file = '\
I would like to play: Volleyball\n\
I would like to play: Volleyball\n\
I do not know how to play: Volleyball\n\
I would like to play: Baseball\n\
I want to learn how to play: Volleyball'
f.write(new_file)
del f  # To Read The File Again


# Next, Printing Lines 1, 3, 4
with open('input.txt', encoding='utf-8', mode='r') as f:
lines = f.readlines()
wanted_lines = [0, 3, 4]
for each_line in wanted_lines:
    print(lines[each_line])
del f  # Just To Save Some Memory

你可以这样做:

with open('Input.txt') as f:
    content = f.readlines()
import pandas as pd
content=pd.unique(content).tolist()

with open('Input.txt') as f:
    content = f.readlines()
result = []
for line in content:
    if line not in result:
        result.append(line)

相关问题 更多 >