Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何逐行检查文本文件以检测是否存在重复?_Python - Fatal编程技术网

Python 如何逐行检查文本文件以检测是否存在重复?

Python 如何逐行检查文本文件以检测是否存在重复?,python,Python,我正试图让我的函数遍历displants.txt上的排序文本,确定是否有重复项,如果有,则返回false,但我似乎无法让它工作。我只是想检测重复,而不是删除它们!有人知道我做错了什么吗 def checkInsultsFile(numInsults=1000, file="Insults.txt"): filename = open(file,'r').readlines() for i in range(0, numInsults): if [i] == [i+

我正试图让我的函数遍历displants.txt上的排序文本,确定是否有重复项,如果有,则返回false,但我似乎无法让它工作。我只是想检测重复,而不是删除它们!有人知道我做错了什么吗

def checkInsultsFile(numInsults=1000, file="Insults.txt"):
    filename = open(file,'r').readlines()
    for i in range(0, numInsults):
        if [i] == [i+1]:
            return False
        else:
            return True

试试这个,我不知道你为什么会有这样的结果

def checkInsultsFile(numInsults=1000, file="Insults.txt"):
    lines = open(file, 'r').readlines()

    dict = {}

    for line in lines:
            dict[line] = dict.get(line,0) + 1

    for k,v in dict.iteritems():
            if v > 1:
                    return True
    return False

如果要检查整个文件,如果行数大于1K,我也不知道为什么要限制numInsults

def checkInsultsFile(file):
    with open(file, 'r') as f:
        lines = [line.strip() for line in f] #puts whole file into list if it's not too large for your RAM
    check = set(lines)
    if len(lines) == len(check):
         return False
    elif len(check) < len(lines):
         return True

checkInsultsFile("Insults.txt")
def检查文件(文件):
打开(文件“r”)作为f:
lines=[line.strip()表示f中的行]#若整个文件对于RAM来说不太大,则将其放入列表中
检查=设置(行)
如果len(行)=len(检查):
返回错误
elif len(检查)
备选方案(逐行运行文件):

def检查文件(文件):
行=[]
打开(文件“r”)作为f:
对于f中的行:
lines.append(line.strip())
检查=设置(行)
如果len(行)=len(检查):
返回错误
elif len(检查)
此函数将把insulars.txt中的所有行放入一个列表中。”“检查”是一个集合,它只会在“行”列表中保留唯一的项。如果行列表等于检查列表,则不存在重复项,并返回False。如果检查列表小于行列表,则您知道存在重复项,并将返回True

或者,您可以使用bash(不知道您的操作系统)。只需指出,有更快/更简单的方法可以做到这一点,除非您的python脚本将以其他方式利用文件中唯一的侮辱列表:

排序侮辱.txt | uniq-c


这类似于在Python中使用集合中的计数器所做的操作,它将为您提供文件中所有行的计数

我的方法比较懒惰,因为一旦发现重复,它的执行就会停止

def checkInsultsFile(filename):
    with open(filename, 'r') as file:
        s = set()
        for line in file:
            if line in s:
                 return True
            s.add(line)
        return False
    except IOError:
        handleExceptionFromFileError()
发生了什么事 最初,
i
0
。包含
0
的单元素列表是否等于包含
1
的单元素列表?显然不是。因此执行转到
else
子句,函数返回
True

它甚至不关心文件的长度或内容,只要它存在并且可读

有效的解决办法 从for
成对(iterable)
中获取提示,它生成成对的
(第1行,第2行)
(第2行,第3行)
(第3行,第4行)
,等等

此外,使用该函数可以简化内部循环

from itertools import tee

def any_consecutive_duplicate_lines(file='Insults.txt'):
    """Return True if the file contains any two consecutive equal lines."""
    with open(file) as f:
        a, b = tee(f)
        next(b, None)
        return any(a_line == b_line for a_line, b_line in zip(a, b))

如果您需要返回,如果有任何重复,我们可以将您的函数简化一点:

def checkdup(file = "insults.txt")
  lines = open(file, 'r').readlines()
  return len(lines) != len(set(lines))
基本上我们做两件事:把txt中的所有行列成一个列表,检查列表中的项目数

len(lines) #the number of insults in your file.
与该列表的唯一元素集合中的项数相同

len(set(lines)) # the number of unique elements of our list, or unique insults

如果他们不一样,一定会有傻瓜

这需要一个新的解决方案。“不工作”是什么意思?很好Morgan-当我运行代码时,即使文件中有重复项,也会返回True。现在,只要它检查第一行,就会返回。所以它只检查第一行,甚至没有检查文件中的任何内容,这里的[i]==[i+1]总是false。它会在第一次检查时自动返回。非常感谢各位的反馈-你知道我如何处理这个问题吗?至于另一篇文章,我看到了,但我并没有试图替换或删除重复的行,我正在尝试检测它们!!我认为这个答案有一定的潜力,但在我看来还不太可能。为什么在python问题中要注意bash可以做什么?有关于柜台的链接吗?当整个文件不可用时,是否真的有必要预先分配它?文件已排序。。。这有用吗?为什么你需要最后一个elsif,有没有可能集合比列表大?也许你不需要去解决那些迂腐的事情(甚至是大多数),但再多一些细节就好了
len(lines) #the number of insults in your file.
len(set(lines)) # the number of unique elements of our list, or unique insults