【问题标题】:How can I find duplicate words in a text file?如何在文本文件中找到重复的单词?
【发布时间】:2016-02-03 01:13:41
【问题描述】:
file_str = input("Enter poem: ")
my_file = open(file_str, "r")
words = file_str.split(',' or ';')

我的计算机上有一个文件,其中包含一首很长的诗,我想看看每行是否有重复的单词(因此它被标点符号分割)。

我有这么多,我不想使用模块或计数器,我更喜欢使用循环。有什么想法吗?

【问题讨论】:

  • 为什么不使用计数器?计数器是正确的解决方案...
  • 在编码时,请不要每个人都决定您只是“不想使用”一个实际的解决方案。您正在尝试解决问题,不要只是扔掉解决方案。
  • 您只想逐行检查?还是整首诗?

标签: python loops for-loop duplicates


【解决方案1】:

您可以使用集合来跟踪看到的项目和重复项:

>>> words = 'the fox jumped over the lazy dog and over the bear'.split()
>>> seen = set()
>>> dups = set()
>>> for word in words:
        if word in seen:
            if word not in dups:
                print(word)
                dups.add(word)
        else:
            seen.add(word)


the
over

【讨论】:

  • Sets 不是最清晰的解决方案,例如,行可以以 'Word' 开头并以 'word' 结尾。这些对于 Python 和集合是不一样的。但对我们来说,这些都是一样的。
  • 这样,你的集合可以有“word”和“Word”。但这些对我们来说都是一样的,这不是最明确的解决方案
  • @JoranBeasley 它们对于美国是重复的,而不是对于 Python。在你的现实生活中,你实际上说:“杰克”和“杰克”不是同一个词。?
  • 是的,它们在编程空间中是截然不同的词......请注意,问题陈述显然没有提到大小写,当没有提到时,假设您正在寻找区分大小写的匹配......如果这是问题陈述的一部分,您明确声明您想要不区分大小写的匹配...默认解释确实是区分大小写
  • 不要迷失在对 OP 可能认为是一个独特词的虚构解释中。请关注问题的实质,即如何仅使用循环和本机对象来识别列表中的重复项。 OP 如何为单词建立等效类是一个任意选择,取决于他或她(与所提出的中心问题无关)。
【解决方案2】:
with open (r"specify the path of the file") as f:
    data =  f.read()
    if(set([i for i in data if f.count(f)>1])):
        print "Duplicates found"
    else:
        print "None"

【讨论】:

    【解决方案3】:

    解决了!!! 我可以用工作程序给出解释

    sam.txt的文件内容

    sam.txt

    你好这是星号你好数据是你好所以你可以移动到 你好

    file_content = []
    resultant_list = []
    repeated_element_list = []
    with open(file="sam.txt", mode="r") as file_obj:
      file_content = file_obj.readlines()
      
    print("\n debug the file content ",file_content)
    
    for line in file_content:
      temp = line.strip('\n').split(" ")    # This will strip('\n') and split the line with spaces and stored as list
      for _ in temp:
        resultant_list.append(_)
      
    print("\n debug resultant_list",resultant_list)
    
    #Now this is the main for loop to check the string with the adjacent string
    for ii in range(0, len(resultant_list)):
      # is_repeated will check the element count is greater than 1. If so it will proceed with identifying duplicate logic
      is_repeated = resultant_list.count(resultant_list[ii])
      if is_repeated > 1:
        if ii not in repeated_element_list:
          for2count = ii + 1
          #This for loop for shifting the iterator to the adjacent string
          for jj in range(for2count, len(resultant_list)):
            if resultant_list[ii] == resultant_list[jj]:
              repeated_element_list.append(resultant_list[ii])
              
    print("The repeated strings are {}\n and total counts {}".format(repeated_element_list, len(repeated_element_list)))
    

    输出:

    debug the file content  ['Hello this is abdul hello\n', 'the data are Hello so you can move to the hello']
    
     debug resultant_list ['Hello', 'this', 'is', 'abdul', 'hello', 'the', 'data', 'are', 'Hello', 'so', 'you', 'can', 'move', 'to', 'the', 'hello']
    
    The repeated strings are ['Hello', 'hello', 'the']
     and total counts 3
    

    谢谢

    【讨论】:

      【解决方案4】:
      def Counter(text):
         d = {}
         for word in text.split():
             d[word]  = d.get(word,0) + 1
         return d
      

      有循环:/

      在标点符号上分开我们

      matches = re.split("[!.?]",my_corpus)
      for match in matches:
          print Counter(match)
      

      【讨论】:

      • collections.Counter 怎么样?
      • 大声笑,他明确表示他不想要它...所以这是一个自定义实现:P ...但是是的,这是正确的答案,恕我直言
      【解决方案5】:

      对于这种文件;

      A hearth came to us from your hearth
      foreign hairs with hearth are same are hairs
      

      这将检查whole诗歌;

      lst = []
      with open ("coz.txt") as f:
          for line in f:
              for word in line.split(): #splited by gaps (space)
                  if word not in lst:
                      lst.append(word)
                  else:
                      print (word)
      

      输出:

      >>> 
      hearth
      hearth
      are
      hairs
      >>> 
      

      如你所见,这里有两个hearth,因为整首诗有3个hearth

      用于逐行检查;

      lst = []
      lst2 = []
      with open ("coz.txt") as f:
          for line in f:
              for word in line.split():
                  lst2.append(word)
                  for x in lst2:
                      if x not in lst:
                          lst.append(x)
                          lst2.remove(x)
      print (set(lst2))
      
      >>> 
      {'hearth', 'are', 'hairs'}
      >>> 
      

      【讨论】:

      • 当您可以使用 O(1) 哈希表搜索和 dict 或 set 代替时,使用线性列表搜索几乎不是一个好的建议。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 2016-09-18
      相关资源
      最近更新 更多