Advertisement
AreTillery

War and Peace

Oct 1st, 2020
1,185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. # Split into a list, then check the elements of the list
  2. with open(r"c:\Users\user\Desktop\warandpeace.txt", "r") as text:
  3.     for line in text:
  4.         line = [word.lower() for word in line.split(" ")]
  5.         war += line.count("war")
  6.         peace += line.count("peace")
  7.  
  8. # split into a list, check the elements of the list using len and list comprehension
  9. with open(r"c:\Users\user\Desktop\warandpeace.txt", "r") as text:
  10.     for line in text:
  11.         line = [word.lower() for word in line.split(" ")]
  12.         war += len([word for word in line if word == "war"])
  13.         peace += len([word for word in line if word == "peace"])
  14.  
  15. # words starting with the specified word
  16. with open(r"c:\Users\user\Desktop\warandpeace.txt", "r") as text:
  17.     for line in text:
  18.         words = [word.lower() for word in line.split(" ")]
  19.         for word in words:
  20.             if word.startswith("war"):
  21.                 war += 1
  22.             if word.startswith("peace"):
  23.                 peace +=1
  24.  
  25. # allow any substring to match
  26. with open(r"c:\Users\user\Desktop\warandpeace.txt", "r") as text:
  27.     for line in text:
  28.         war += line.count("war")
  29.         peace += line.count("peace")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement