简体   繁体   中英

find UnRepeated word in two list

i Have different words in two lists and also i have a commit words i need to get out the different words in two lists for Example list one:

apple
cut
chance

list two :

apple
cut
chance
help
there

my shot not working it give me repeated and there is unrepeated words my script

wcode = open('wcode.txt', 'r')
rcode = open('rcode.txt', 'r')
for new in wcode :
    if wcode.read() in rcode.read() :
        print(' Repeated ')
    else :
        print(' UnRepeated !!!' + '\n' + new)

It sounds like you want the symmetric difference between the two lists. For finding this, I would use Python's set operations.

After you've read the contents of yours files into lists, you can convert them to sets and compute the symmetric difference as shown below. At the end, you can convert the result back to a list if you want.

wcode = ['a', 'list', 'of', 'words', 'that', 'you', 'read', 'from', 'wcode', 'txt']
rcode = ['a', 'list', 'of', 'words', 'that', 'she', 'read', 'from', 'rcode', 'txt']
wcode = set(wcode)
rcode = set(rcode)

difference = wcode.symmetric_difference(rcode)

assert difference == {'she', 'you', 'wcode', 'rcode'}
final_result = list(difference)

Use sets:

s1 = {"apple", "cut", "chance"}
s2 = {"apple", "cut", "chance", "help", "there"}

print("Repeated: " + ", ".join(s1 & s2))
print("Not repeated: " + ", ".join(s1.symmetric_difference(s2)))

Edit

The bigger issue is that you should probably be consuming your files very differently:

wcode, rcode = (set(open(fn, "rb").read().splitlines()) for fn in [
    "rcode.txt",
    "wcode.txt"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM