Sep-12-2019, 05:31 PM
I've been trying to figure this one out, but all I could find is people having problem with duplication instead of adding it as a feature.
I have this code below and it copies same matched words from two text files, but if there is two or more of same matched word it only copies it once. I need a function if there are two or more of the same matched words copy both of them.
Example: Analyze text1 contains(Some Random Text About Value Value Or More) text2 contains(Value Add More) code would copy 'Value' only once, I need it to copy both values so it says 'Value, Value'
Thanks to Larz60 one more time for helping me with code below.
I have this code below and it copies same matched words from two text files, but if there is two or more of same matched word it only copies it once. I need a function if there are two or more of the same matched words copy both of them.
Example: Analyze text1 contains(Some Random Text About Value Value Or More) text2 contains(Value Add More) code would copy 'Value' only once, I need it to copy both values so it says 'Value, Value'
Thanks to Larz60 one more time for helping me with code below.
import os
def get_words(filename):
wordlist = []
with open(filename) as fp:
for line in fp:
wordsinline = line.strip().split()
for item in wordsinline:
if item not in wordlist:
wordlist.append(item)
return wordlist
def find_common_words(filename1, filename2):
wordlist1 = []
wordlist2 = []
matching_words = []
wordlist1 = get_words(filename1)
wordlist2 = get_words(filename2)
matching_words = set(wordlist1) & set(wordlist2)
print(matching_words)
def testit():
# Assert in same directory as code
os.chdir(os.path.abspath(os.path.dirname(__file__)))
filename1 = 'words1.txt'
filename2 = 'words2.txt'
find_common_words(filename1, filename2)
if __name__ == '__main__':
testit()
