Hi

I am trying to do a simple thing but I am stuck :(.

Basically, I have 4 texts. I want to compare text 2 with text 1 and text 4 with text 3, then save these differences into two different texts so that these differences can then be compared.

I am stuck with saving the differences into another text. Here is the code so far

# I have 4 texts as given, need to find the difference between text2 and text1 and difference between text4 and text3
# The problem is how to save these differences into another text string
# so lets say Difference (text2 - text1)  = difference
# Difference (text4 - text3) = difference1
# so that I can compare these 2 difference files
import difflib

text1 = """Aat
Bat
Cat
Dat
Eat
Fat
Gat
Hat
Iat
Jat
Kat
Lat
Mat
Nat
Oat
Pat
Qat
Rat
Sat
Tat
Uat
Vat
Wat
Xat
Yat
Zat
""".splitlines(1)

text2 = """Aat
Beat
Coat
Dat
Eats
Fact
Gat
Hate
Iat
Jat
Kat
Lat
Mate
Nat
Oaty
Pats
Qat
Rate
Satire
Tat
Uat
Vat
Wat
Xat
Yat
Zat
""".splitlines(1)

text3 = """Aat
Bait
Caveat
Data
East
Fate
Goat
Hit
Iat
Jot
Kit
Let
Mat
Not
Oat
Pat
Quit
Rot
Sit
Tat
Uat
Vet
Watts
Xat
Yat
Zat
""".splitlines(1)

text4 = """Aat
Bait
Caveat
Data
East
Fate
Goat
Hit
Iat
Jot
Kit
Let
Mate
Not
Oaty
Pats
Quit
Rot
Sit
Tat
Uat
Vet
Watts
Xat
Yat
Zat
""".splitlines(1)

d = difflib.Differ()

result = list(d.compare(text1, text2))
result1 = list(d.compare(text3, text4))

print result
print
print result1

print '-'*10    
print "lines different in text 2 from text 1:"

for line in result:
  if line[0] == '+':
    print line
    

print '-'*10    
print "lines different in text 4 from text 3:"
for line1 in result1:
  if line1[0] == '+':
    print line1
    
# this produces the differences one by one
# i want to save all these differences into another variable

#print difference
#print difference1

Can anyone suggest on how to do this?

many thanks

Recommended Answers

All 3 Replies

You could change your last lines to something like this ...

print '-'*10    
print "lines different in text 2 from text 1:"
difference21 = ""
for line in result:
  if line[0] == '+':
    print line
    difference21 += line

print '-'*10    
print "lines different in text 4 from text 3:"
difference43 = ""
for line1 in result1:
  if line1[0] == '+':
    print line1
    difference43 += line1
    
print '-'*10  
print difference21
print '-'*10  
print difference43

Thanks a lot Vegaseat! Its working fine

I am currently using this module difflib for a new app i am working on. Nice one. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.