【问题标题】:How do I compare two strings in python if order does not matter?如果顺序无关紧要,如何比较python中的两个字符串?
【发布时间】:2014-03-21 03:53:22
【问题描述】:

我有两个类似的字符串

string1="abc def ghi"

string2="def ghi abc"

如何在不分词的情况下使这两个字符串相同?

【问题讨论】:

  • 你是什么意思'是一样的'?你对字符串相等的定义是什么?
  • 这两个字符串相同。重要的是顺序字符串。
  • 如果您的问题得到解决,请将任何答案标记为已接受

标签: python string python-2.7 string-comparison


【解决方案1】:

似乎问题不是关于字符串相等,而是 sets 相等。您可以通过拆分字符串并将它们转换为集合来比较它们:

s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' '))
set2 = set(s2.split(' '))
print set1 == set2

结果将是

True

【讨论】:

  • 使用 lambda 忽略大小写 s1 = 'abc def ghi' s2 = 'def ghi Abc' set1 = set(map(lambda word: word.lower(),s1.split(' '))) set2 = set(map(lambda word: word.lower(),s2.split(' '))) print(set1 == set2) Demo
  • @Abhijeet map 中不需要,因为您可以在拆分之前对字符串大小写进行规范化
【解决方案2】:

如果你想知道两个字符串是否相等,你可以简单地做

print string1 == string2

但是如果你想知道它们是否有相同的字符集并且它们出现的次数相同,你可以使用collections.Counter,像这样

>>> string1, string2 = "abc def ghi", "def ghi abc"
>>> from collections import Counter
>>> Counter(string1) == Counter(string2)
True

【讨论】:

    【解决方案3】:
    >>> s1="abc def ghi"
    >>> s2="def ghi abc"
    >>> s1 == s2  # For string comparison 
    False
    >>> sorted(list(s1)) == sorted(list(s2)) # For comparing if they have same characters. 
    True
    >>> sorted(list(s1))
    [' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    >>> sorted(list(s2))
    [' ', ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    

    【讨论】:

      【解决方案4】:

      为此,您可以在 python 中使用默认的 difflib

      from difflib import SequenceMatcher
      
      def similar(a, b):
          return SequenceMatcher(None, a, b).ratio()
      

      然后调用similar()为

      similar(string1, string2)
      

      它将返回比较为 ,ratio >= 阈值以获得匹配结果

      【讨论】:

        【解决方案5】:

        直接比较中的平等:

        string1 = "sample"
        string2 = "sample"
        
        if string1 == string2 :
            print("Strings are equal with text : ", string1," & " ,string2)
        else :
            print ("Strings are not equal")
        

        字符集的相等性:

        string1 = 'abc def ghi'
        string2 = 'def ghi abc'
        
        set1 = set(string1.split(' '))
        set2 = set(string2.split(' '))
        
        print set1 == set2
        
        if string1 == string2 :
            print("Strings are equal with text : ", string1," & " ,string2)
        else :
            print ("Strings are not equal")
        

        【讨论】:

          【解决方案6】:

          类似这样的:

          if string1 == string2:
              print 'they are the same'
          

          更新:如果要查看每个子字符串是否可能存在于另一个中:

          elem1 = [x for x in string1.split()]
          elem2 = [x for x in string2.split()]
          
          for item in elem1:
              if item in elem2:
                  print item
          

          【讨论】:

            【解决方案7】:

            如果只需要检查两个字符串是否完全相同,

            text1 = 'apple'
            
            text2 = 'apple'
            
            text1 == text2
            

            结果是

            True
            

            如果需要匹配百分比,

            import difflib
            
            text1 = 'Since 1958.'
            
            text2 = 'Since 1958'
            
            output = str(int(difflib.SequenceMatcher(None, text1, text2).ratio()*100))
            

            匹配百分比输出将是,

            '95'
            

            【讨论】:

              【解决方案8】:

              我将提供几种解决方案,您可以选择满足您需求的一种:

              1) 如果您只关心字符,即两个字符串中的字符相同且频率相同,请使用:

              ''.join(sorted(string1)).strip() == ''.join(sorted(string2)).strip()
              

              2) 如果您还关心两个字符串中的空格(空白字符)的数量,那么只需使用以下 sn-p:

              sorted(string1) == sorted(string2)
              

              3) 如果您正在考虑单词但不考虑它们的顺序并检查两个字符串是否具有相同的单词频率,无论它们的顺序/出现如何,那么可以使用:

              sorted(string1.split()) == sorted(string2.split())
              

              4) 扩展上述内容,如果您不关心频率计数,而只需要确保两个字符串包含相同的 set 单词,那么您可以使用以下内容:

              set(string1.split()) == set(string2.split())
              

              【讨论】:

              • 对于第三个用例collection.Counter 似乎比使用sorted 更明显
              【解决方案9】:

              我认为 difflib 是一个很好的库来完成这项工作

                 >>>import difflib 
                 >>> diff = difflib.Differ()
                 >>> a='he is going home'
                 >>> b='he is goes home'
                 >>> list(diff.compare(a,b))
                   ['  h', '  e', '   ', '  i', '  s', '   ', '  g', '  o', '+ e', '+ s', '- i', '- n', '- g', '   ', '  h', '  o', '  m', '  e']
                  >>> list(diff.compare(a.split(),b.split()))
                    ['  he', '  is', '- going', '+ goes', '  home']
              

              【讨论】:

                【解决方案10】:

                打开两个文件 然后通过拆分单词内容来比较它们;

                log_file_A='file_A.txt'
                
                log_file_B='file_B.txt'
                
                read_A=open(log_file_A,'r')
                read_A=read_A.read()
                print read_A
                
                read_B=open(log_file_B,'r')
                read_B=read_B.read()
                print read_B
                
                File_A_set = set(read_A.split(' '))
                File_A_set = set(read_B.split(' '))
                print File_A_set == File_B_set
                

                【讨论】:

                  【解决方案11】:

                  如果你想要一个非常简单的答案:

                  s_1 = "abc def ghi"
                  s_2 = "def ghi abc"
                  flag = 0
                  for i in s_1:
                      if i not in s_2:
                          flag = 1
                  if flag == 0:
                      print("a == b")
                  else:
                      print("a != b")
                  

                  【讨论】:

                  • 在这里使用 '==' 运算符是相当简单且正确的答案。
                  • @HaSeeBMiR 和 != :)
                  【解决方案12】:

                  尝试将两个字符串转换为大写或小写。然后就可以使用==比较运算符了。

                  【讨论】:

                    【解决方案13】:

                    这是一个非常基本的示例,但是在逻辑比较 (==) 或 string1.lower() == string2.lower() 之后,尝试一些关于两个字符串之间距离的基本度量可能会很有用。

                    您可以在任何地方找到与这些或其他一些指标相关的示例,也可以尝试使用fuzzywuzzy 包(https://github.com/seatgeek/fuzzywuzzy)。

                    import Levenshtein
                    import difflib
                    
                    print(Levenshtein.ratio('String1', 'String2'))
                    print(difflib.SequenceMatcher(None, 'String1', 'String2').ratio())
                    

                    【讨论】:

                      【解决方案14】:

                      您可以使用简单的循环来检查两个字符串是否相等。 .但理想情况下,您可以使用类似 return s1==s2

                      s1 = 'hello'
                      s2 = 'hello'
                      
                      a = []
                      for ele in s1:
                          a.append(ele)
                      for i in range(len(s2)):
                          if a[i]==s2[i]:
                              a.pop()
                      if len(a)>0:
                          return False
                      else:
                          return True
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-05-09
                        • 1970-01-01
                        • 1970-01-01
                        • 2018-05-19
                        • 2010-12-09
                        • 2022-09-30
                        • 1970-01-01
                        相关资源
                        最近更新 更多