Python 为文本文件的行创建排名并仅保留顶行
假设我有一个文本文件,其中有数千行,格式如下:Python 为文本文件的行创建排名并仅保留顶行,python,python-3.x,text,Python,Python 3.x,Text,假设我有一个文本文件,其中有数千行,格式如下: Word Number1 Number2 在这个文本文件中,“单词”实际上是一些从一行到另一行变化的单词,数字也同样在变化数字。然而,有些词是相同的。。。考虑下面的例子: Hello 5 7 Hey 3 2 Hi 7 3 Hi 5 2 Hello 1 4 Hey 5 2 Hello 8 1 什么是python脚本,它读取文本文件并只保留任何给定单词中包含最高数字1的行(删除所有不满足此条件的行)?上述示例使用此类脚本的输出将为: Hi 7 3
Word Number1 Number2
在这个文本文件中,“单词”实际上是一些从一行到另一行变化的单词,数字也同样在变化数字。然而,有些词是相同的。。。考虑下面的例子:
Hello 5 7
Hey 3 2
Hi 7 3
Hi 5 2
Hello 1 4
Hey 5 2
Hello 8 1
什么是python脚本,它读取文本文件并只保留任何给定单词中包含最高数字1的行(删除所有不满足此条件的行)?上述示例使用此类脚本的输出将为:
Hi 7 3
Hey 5 2
Hello 8 1
注意:输出中的行顺序无关,重要的是满足上述条件。此外,如果对于给定的字,两行或多行的最高数字1相同,则输出应仅保留其中一行,以便输出中任何字只出现一次
我不知道如何处理删除方面,但我可以猜测(可能是错误的)第一步是从文本文件中的所有行中列出一个列表,即
List1 = open("textfile.txt").readlines()
无论如何,非常感谢您的帮助 您可以尝试以下方法:
f = [i.strip('\n').split() for i in open('the_file.txt')]
other_f = {i[0]:map(int, i[1:]) for i in f}
for i in f:
if other_f[i[0]][0] < int(i[1]):
other_f[i[0]] = map(int, i[1:])
new_f = open('the_file.txt', 'w')
for a, b in other_f.items():
new_f.write(a + " "+' '.join(map(str, b))+"\n")
new_f.close()
您可以尝试以下方法:
f = [i.strip('\n').split() for i in open('the_file.txt')]
other_f = {i[0]:map(int, i[1:]) for i in f}
for i in f:
if other_f[i[0]][0] < int(i[1]):
other_f[i[0]] = map(int, i[1:])
new_f = open('the_file.txt', 'w')
for a, b in other_f.items():
new_f.write(a + " "+' '.join(map(str, b))+"\n")
new_f.close()
因为文件对象是可编辑的,所以不必预先进行读取。因此,让我们打开该文件,然后使用for循环对其进行迭代
fin = open('sometext.txt')
我们创建一个字典来保存结果
topwords = dict()
现在在文件中的行上迭代:
for line in fin:
根据空格的位置(split()的默认行为),我们去掉新行字符并将行拆分为单个字符串
我们检查是否已经看到这个词,如果是,我们检查第一个值是否大于先前存储的第一个值
if word in topwords:
if val1 > topwords[word][0]:
topwords[word] = [val1, val2]
else:
topwords[word] = [val1, val2]
一旦我们完成了对所有单词的解析,我们就返回并迭代上面的单词,并将结果打印到屏幕上
for word in topwords:
output = '{} {} {}'.format(word, *topwords[word])
print(output)
最后的脚本如下所示:
fin = open('sometext.txt')
topwords = dict()
for line in fin:
word, val1, val2 = line.strip().split()
val1 = int(val1)
if word in topwords:
if val1 > topwords[word][0]:
topwords[word] = [val1, val2]
else:
topwords[word] = [val1, val2]
for word in topwords:
output = '{} {} {}'.format(word, *topwords[word])
print(output)
因为文件对象是可编辑的,所以不必预先进行读取。因此,让我们打开该文件,然后使用for循环对其进行迭代
fin = open('sometext.txt')
我们创建一个字典来保存结果
topwords = dict()
现在在文件中的行上迭代:
for line in fin:
根据空格的位置(split()的默认行为),我们去掉新行字符并将行拆分为单个字符串
我们检查是否已经看到这个词,如果是,我们检查第一个值是否大于先前存储的第一个值
if word in topwords:
if val1 > topwords[word][0]:
topwords[word] = [val1, val2]
else:
topwords[word] = [val1, val2]
一旦我们完成了对所有单词的解析,我们就返回并迭代上面的单词,并将结果打印到屏幕上
for word in topwords:
output = '{} {} {}'.format(word, *topwords[word])
print(output)
最后的脚本如下所示:
fin = open('sometext.txt')
topwords = dict()
for line in fin:
word, val1, val2 = line.strip().split()
val1 = int(val1)
if word in topwords:
if val1 > topwords[word][0]:
topwords[word] = [val1, val2]
else:
topwords[word] = [val1, val2]
for word in topwords:
output = '{} {} {}'.format(word, *topwords[word])
print(output)
您可以将这些行存储在
dict
中,并将单词作为键。为了简化操作,可以存储一个元组,其中包含第一个数字字段的值(转换为整数,否则将按字典顺序排序)和行
我们使用dict.setdefault
以防第一次遇到这个词
highest = {}
with open('text.txt') as f:
for line in f:
name, val, _ = line.split(' ', 2)
val = int(val)
if val > highest.setdefault(name, (val, line))[0]:
highest[name] = (val, line)
out = [tup[1] for name, tup in highest.items()]
print(''.join(out))
# Hey 5 2
# Hello 8 1
# Hi 7 3
您可以将这些行存储在
dict
中,并将单词作为键。为了简化操作,可以存储一个元组,其中包含第一个数字字段的值(转换为整数,否则将按字典顺序排序)和行
我们使用dict.setdefault
以防第一次遇到这个词
highest = {}
with open('text.txt') as f:
for line in f:
name, val, _ = line.split(' ', 2)
val = int(val)
if val > highest.setdefault(name, (val, line))[0]:
highest[name] = (val, line)
out = [tup[1] for name, tup in highest.items()]
print(''.join(out))
# Hey 5 2
# Hello 8 1
# Hi 7 3
首先是列表,第一列和第二列为从高到低的键
然后删除重复的项目
list1 = open(r'textfile.txt').read().splitlines()
output = sorted(list1, key=lambda x:(x.split()[0], int(x.split()[1])), reverse=True)
uniq_key = []
for i in sorted_dat:
key = i.split()[0]
if key in uniq_key:
output.remove(i)
else:
uniq_key.append(key)
>>> output
['Hi 7 3', 'Hey 5 2', 'Hello 8 1']
首先是列表,第一列和第二列为从高到低的键
然后删除重复的项目
list1 = open(r'textfile.txt').read().splitlines()
output = sorted(list1, key=lambda x:(x.split()[0], int(x.split()[1])), reverse=True)
uniq_key = []
for i in sorted_dat:
key = i.split()[0]
if key in uniq_key:
output.remove(i)
else:
uniq_key.append(key)
>>> output
['Hi 7 3', 'Hey 5 2', 'Hello 8 1']
为什么不用口述呢?或者,如果顺序很重要,一个有序的口述?每次你遇到一个单词,检查它是否在dict中,并相应地采取行动。如果有两行具有相同的单词和相同的数字-你想保留两行还是仅保留一行?我只想保留一行(尽管我忘了提到这一点,因为考虑到我的特定文本文件的性质,这不应该发生)-我会在问题上加上这个为什么不使用口述?或者,如果顺序很重要,一个有序的口述?每次你遇到一个单词,检查它是否在dict中,并相应地采取行动。如果有两行具有相同的单词和相同的数字-你想保留两行还是仅保留一行?我只想保留一行(尽管我忘了提到这一点,因为考虑到我的特定文本文件的性质,这不应该发生)-我将把它添加到问题中,这里不需要readlines()调用。Python将很乐意解析由open()调用创建的file对象。不必要地使用readlines()会在内存中创建一个列表,而open()调用本质上会创建一个iterable对象(从而节省一些处理时间和内存)。@E.Ducateme感谢您指出这一点。请参阅我最近的编辑。此处不需要readlines()调用。Python将很乐意解析由open()调用创建的file对象。不必要地使用readlines()会在内存中创建一个列表,而open()调用本质上会创建一个iterable对象(从而节省一些处理时间和内存)。@E.Ducateme感谢您指出这一点。请参阅我最近的编辑。
val1
是一个字符串,因此您是按字典顺序(而不是数字顺序)比较值。因此,您将使用“2”>“12”
val1
是一个字符串,因此您是按字典顺序(而不是数字顺序)比较值。因此,您将拥有“2”>“12”