[英]How do I compare two strings in python?
我有兩個字符串
string1="abc def ghi"
和
string2="def ghi abc"
如何在不破壞單詞的情況下使這兩個字符串相同?
似乎問題不是關於字符串相等,而是關於集合相等。 您只能通過拆分字符串並將它們轉換為集合來以這種方式比較它們:
s1 = 'abc def ghi'
s2 = 'def ghi abc'
set1 = set(s1.split(' '))
set2 = set(s2.split(' '))
print set1 == set2
結果將是
True
如果你想知道兩個字符串是否相等,你可以簡單地做
print string1 == string2
但是如果你想知道它們是否有相同的字符集並且它們出現的次數相同,你可以使用collections.Counter
,像這樣
>>> string1, string2 = "abc def ghi", "def ghi abc"
>>> from collections import Counter
>>> Counter(string1) == Counter(string2)
True
>>> 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']
直接比較中的相等性:
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")
為此,您可以在 python 中使用默認的 difflib
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
然后將 similar() 稱為
similar(string1, string2)
它將返回 compare as ,ratio >= threshold 以獲得匹配結果
像這樣的東西:
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
如果您只需要檢查兩個字符串是否完全相同,
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'
我將提供幾種解決方案,您可以選擇滿足您需求的一種:
1)如果您只關心字符,即相同的字符並且在兩個字符串中每個字符的頻率相等,請使用:
''.join(sorted(string1)).strip() == ''.join(sorted(string2)).strip()
2)如果您還關心兩個字符串中的空格(空白字符)的數量,那么只需使用以下代碼片段:
sorted(string1) == sorted(string2)
3)如果您正在考慮單詞而不是它們的排序並檢查兩個字符串是否具有相同的單詞頻率,無論它們的順序/出現如何,那么可以使用:
sorted(string1.split()) == sorted(string2.split())
4)擴展上面的,如果你不關心頻率計數,而只需要確保兩個字符串包含相同的單詞集,那么你可以使用以下內容:
set(string1.split()) == set(string2.split())
我認為 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']
打開兩個文件,然后通過拆分其單詞內容來比較它們;
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
如果你想要一個非常簡單的答案:
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")
嘗試將兩個字符串轉換為大寫或小寫。 然后你可以使用==
比較運算符。
這是一個非常基本的例子,但在邏輯比較 (==) 或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())
您可以使用簡單的循環來檢查兩個字符串是否相等。 .但理想情況下,您可以使用類似 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.