Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
im having probelms with my python program?
this is my program
def main():
# the names of the files
file1 = "preTestExam01.txt"
file2 = "preTestExam02.txt"
checkForWord(file1,file2)
def checkForWord(f1,f2):
theFile = open(f1,'r')
theFile2 = open(f2,'r')
counter = 0
for word in theFile.read().split():
for word in theFile2.read().split():
if word in theFile:
counter += 1
print(word,counter)
main()
this is what i have to do
write a script that for every word that is in preTestExam01.txt checks many of them are in the preTestExam02.txt. your program shall print the counters for all words fomr preTestExam01.txt found in preTestExam01.txt.
my problem is that it doesnt want to count how many times the word appears in the files.
2 Answers
- brilliant_movesLv 76 years agoFavorite Answer
This seems to work, Omar:
def main():
... # the names of the files
... file1 = "preTestExam01.txt"
... file2 = "preTestExam02.txt"
... checkForWord(file1,file2)
def checkForWord(f1,f2):
... theFile = open(f1,'r')
... theFile2 = open(f2,'r')
... words2 = theFile2.read().split()
... for word in theFile.read().split():
... ... counter = 0
... ... for word2 in words2:
... ... ... if word == word2:
... ... ... ... counter += 1
... ... print(word,counter)
main()
#Note: I've used "... " in place of tabs (which Y!Answers removes)
- amania_rLv 76 years ago
You can do it without the loops using the set intersection feature of Python:
words1 = theFile1.read().split()
words2 = theFile2.read().split()
print len(set(words1) & set(words2))