-1

I need to slice a word from from a sentence in a list and then cound how many times this word has been used in a file. I started by reading the file in a list. This put a whole sentence into one position of a list. Im looking to slice the sentence from character 7 - 14, cutting the word i need out and then counting how many times that word has been used in the whole file or rest of the list! need help!

Tom
  • 19
  • 2
  • 8

3 Answers3

0

Im looking to slice the sentence from character 7 - 14

You should look at string slicing in Python. To get the characters in a string from position 7 (inclusive) to 14 (exclusive):

example = "this is an example string"
what_you_want = example[7:14]
Community
  • 1
  • 1
Brendan Long
  • 53,280
  • 21
  • 146
  • 188
0

You can use the split method to turn a sentence into a list of words like this:

sentence = "this is a sentence"
setence_list = sentence.split(" ")

turns our sentence into

['this', 'is', 'a', 'sentence']

Which allows you to index the sentence with something like: list[2]

You can essentially do the same thing with the file and then use a for loop to count how many times the word happens.

ecline6
  • 896
  • 8
  • 15
0
file = open("file.txt","r")
substring = file.readline()[6:14]
print(file.read().replace("\n"," ").split(" ").count(substring+1))
Aleksander S
  • 368
  • 1
  • 10