AttributeError: 'str' object has no attribute 'slice'
I'm trying to print the last word if every line in a file but while slicing the last word of each line (each line in file is a string) I'm getting the above mentione error.
This is the text inside my file: X-DSPAM-Confidence: 0.8475 X-DSPAM-Confidence: 0.6178 X-DSPAM-Confidence: 0.6961 X-DSPAM-Confidence: 0.7565
I'm trying to add the float values in the code and find its avg
Here's the code:
```
python code
```
sum =0
count = 0
myFile = open("C:/Users/Desktop/PDS/sample.txt", "r")
for line in myFile:
count += 1
line = line.strip()
if(line.startswith("X-DSPAM-Confidence")):
line = line.slice(-1,-7)
sum += line
myFile.close()
print("Sum: ",sum)
print("Avg: ", sum/count)
To extract the last word from each line in a file, you can use Python's string manipulation methods like split to split each line into words and then access the last word.
with open('your_file.txt', 'r') as file:
for line in file:
words = line.strip().split()
if words:
last_word = words[-1]
print(last_word)