gpt4 book ai didi

Python 文本文件中的重复单词

转载 作者:行者123 更新时间:2023-11-30 23:09:23 26 4
gpt4 key购买 nike

我有一个txt文件

文本文件如下所示:

仍然无法工作。

['None']['Vega~']['Vega~']['Vega~']['8^)->-<']['violence']['puker']['Zanaz']['Funk']['8^)->-<']['8^)->-<']['8^)->-<']['Vega~']['violence']['Zanaz']['Funk']['puker']['Vega~']['Vega~']['Vega~']['8^)->-<']['violence']['puker']['Zanaz']['None']['Lawn']['Lawn']['Lawn']['Leafy']['Judge69']['David']['lilwade']['Pity.']['artofwar']['Hazecloud']['Lawn']['Lawn']['Lawn']['Judge69']['Leafy']['David']['lilwade']['Hazecloud']['Lawn']['Lawn']['Lawn']['Leafy']['David']['Pity.']['lilwade']['artofwar']['Judge69']

我需要删除所有重复项,因此每个名称只能显示一次,而且必须保持它们所在的顺序。

   fo = open('C:\Python26\myfile.txt','r')
name_cache = fo.readlines()
typea = name_cache[0]

def unique_list(l):
ulist = []
[ulist.append(x) for x in l if x not in ulist]
return ulist

mast =' '.join(unique_list(typea.split()))
print mast

最佳答案

首先删除前导 [ 和尾随 ]。然后在][分割。例如

>>> x="['None']['Vega~']['Vega~']"
>>> x.rstrip(']').lstrip('[').split('][')
["'None'", "'Vega~'", "'Vega~'"]

然后调用您的unique_list

>>> y = x.rstrip(']').lstrip('[').split('][') 
>>> unique_list(y)
["'None'", "'Vega~'"]

然后您可以轻松地将其格式化为您想要的任何内容(即字符串)。

请注意,rstriplstrip 均为 O(n)。因此,最好执行x[1:-1]。这假设您 100% 确定输入是给定的形式(以 [ 开头,以 ] 结尾)

这与散列每个单词(添加到 python 集合)具有相同的 O(n) 时间复杂度,但保持原始顺序,并可以使用您的(非常简洁的)unique_list 函数。

关于Python 文本文件中的重复单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31237690/

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