How do i print only (bottem) part of a dictionary in python3? - python

I have created a dictionary by counting a list of positives words(positives.txt) over a list of tweets(tweets.txt).
Now im trying to print the top 5 used postitive words with respective scores.
I have managed to sort the scores and able to print the whole list of words with their scores, like:
(rest of list...)
wordx 5
wordy 28
wordz 35
My goal is to print (just) a top 3:
wordz 35
wordy 28
wordx 5
I tried giving indexes en subscripts at different places but keep getting error messages like:
Traceback (most recent call last):
print(word[3], score[3])
IndexError: string index out of range
print(word[0:5], score[0:5])
TypeError: 'int' object is not subscriptable
Current Code:
def positive_word(tweets, positives):
"""prints the top 5 most used positive words"""
x = {}
#for l in range(5):
for l in range(len(positives)):
x[positives[l]] = 0
#for m in range (5):
for m in range (len(tweets)):
#for n in range (5):
for n in range (len(positives)):
if positives[n] in tweets[m]:
x[positives[n]] += 1
for word, score in sorted(x.items(), key = lambda key : key[1]):
print(word, score)

Related

Print value until string index is 0

I am passing dot separated key as a argument. I have used split(".") and then print the value data. Here is my code:
desc = str(sys.argv[1])
st = desc.split(".")
i = 0
print (len(st))
for i in range(len(st)):
for ch in st:
st[i] = ch
print (st[i])
i += 1
print(i)
#print(data[st1][st2]..[stn])
I am getting the output as
3
db
1
dap
2
nodes
3
db
2
db
3
Traceback (most recent call last):
File "getvar.py", line 17, in <module>
st[i] = ch
IndexError: list assignment index out of range
I want the data[db][dap][nodes] which will give me the correct value. How should I proceed?
You are confusing 2 loops : for item in items and for i in range.
When you use i in range the max value in length -1 because indexes are zero based.
when you have used split st is an array of values so the line st[i] = ch is reloading the value back where is was read from.
Here I give both syntaxes of the loop. You will observe that print(st) before the loops gives the result that you want.
desc="10.12.45.35.66.28"
#desc = str(sys.argv[1])
st = desc.split(".")
print([st])
print ("length:",len(st))
for j in range(len(st)-1):
print (j," -> ", st[j])
i = 0
for ch in st:
st[i] = ch
print (i," -> ", st[i])
i += 1

List Comprehension Showing IndexError

I'm creating a hangman game. I came up with an idea to replace underscores with a letter. First the user inputs their guess (the letter "c" in this case). I search through a list containing the letters of the unknown word creating a list with the indices of each time there is a hit for that letter. Then I search through the list of underscores and replace all the underscores with the letter using the index list I created. However, I'm getting an error:
IndexError: list index out of range.
What am I doing wrong in the below code?
y = "cctcc"
to_modify = ["_", "_", "_","_", "_"]
replacements = list(y)
user_input = input()
indexes = [i for i, j in enumerate(replacements) if j == user_input]
print(indexes)
for index in indexes:
to_modify[indexes[index]] = replacements[index]
print(to_modify)
Output:
[0, 1, 3, 4]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-25-be2b07a156e5> in <module>()
10 print(indexes)
11 for index in indexes:
---> 12 to_modify[indexes[index]] = replacements[index]
13
14 print(to_modify)
IndexError: list index out of range
This section of the code is already looping over the indices:
for index in indexes:
to_modify[indexes[index]] = replacements[index]
If indexes contains [0,1,3,4], when index loops to 4 it's trying to access indexes[4] which is out of range, just use the indexes you're getting from the loop:
for index in indexes:
to_modify[index] = replacements[index]

How to fix my code's error "List index out of range"

How do I fix the error my code comes up with the following?
Traceback (most recent call last):
File "main.py", line 143, in <module>
print(question_list2[random_int])
IndexError: list index out of range
This is the code in question:
question_list2 = []
question_list2.append(" the marines are ___ based opreatives ")
question_list2.append(" for under water travel marines use _____ ")
question_list2.append(" the avergae marine trains for _ weeks ")
answer_list2 = []
answer_list2.append("sea")
answer_list2.append("subamrines")
answer_list2.append("13")
top_index = 4
correct = 0
for i in range (0,4):
random_int = random.randint(0,top_index)
print(question_list2[random_int])
top_index = top_index - 1
user_answer1 = input("fill in the blank with the correct word ")
if user_answer == answer_list1[random_int]:
correct = correct + 3
del question_list1[random_int]
del answer_list1[random_int]
From the random docs
random.randint(a, b)
Return a random integer N such that a <= N <= b
This means that:
top_index = 4
random_int = random.randint(0,top_index)
Has the possibility of setting random_int to 3 or 4 which are outside the range of your list which only has three items with index 0, 1, and 2.
Rather than mutating your lists and using indexes, it might be easier to make a list of indexes, shuffle it, then iterate over it:
indexes = random.sample(range(0, len(question_list)), k = len(question_list))
for i in indexes:
# etc...
If you kept the questions and answers together in a single list, you could do away with the indexes altogether. This would be a good use for named tuples
import random
from collections import namedtuple
qa = namedtuple('QA', ['question', 'answer'])
question_list = [
qa(" the marines are ___ based opreatives ", 'sea'),
qa(" for under water travel marines use _____ ",'submarines'),
qa(" the avergae marine trains for _ weeks ", '13')
]
random.shuffle(question_list)
correct = 0
for qa in question_list:
print(qa.question)
user_answer = input("fill in the blank with the correct word ")
if user_answer == qa.answer:
correct = correct + 1
I believe that you only have three things on your list. The range should be range(0,3) and maybe your top_index should be top_index = 2.
Since the indexes on your list are [0,1,2]
The first item in list > index = 0
The second item in list > index = 1
The third item in list > index = 2

IndexError: list index out of range PYTHON (w/o using for loop)

I am trying to find averages from a text file. The text file has columns of numbers and I want to find the average of each column. I get the follwoing error:
IndexError: list index out of range
The code I am using is:
import os
os.chdir(r"path of my file")
file_open = open("name of my file", "r")
file_write = open ("average.txt", "w")
line = file_open.readlines()
list_of_lines = []
length = len(list_of_lines[0])
total = 0
for i in line:
values = i.split('\t')
list_of_lines.append(values)
count = 0
for j in list_of_lines:
count +=1
for k in range(0,count):
print k
list_of_lines[k].remove('\n')
for o in range(0,count):
for p in range(0,length):
print list_of_lines[p][o]
number = int(list_of_lines[p][o])
total + number
average = total/count
print average
The error is in line
length = len(list_of_lines[0])
Please let me know if I can provide anymore information.
The issue is you are trying to get the length of something in the array, not the array itself.
Try this:
length = len(list_of_lines)
You wrote length = len(list_of_lines[0])
line_of_lines is defined right above this line, as a list with 0 items in it. As a result, you cannot select the first item (index number 0) because index number 0 does not exist. Therefore, it is out of range.

String Index Out of Range Error in Python

I keep getting an "IndexError: string index out of range" error message when I try to execute this code:
#function countLetters(word,letter) should count the number of times
#a particular letter appears in a word.
def countLetters(word, letter):
count=0
wordlen=len(word)
num=0
wordletter=""
while(num<=wordlen):
wordletter=word[num]
if(wordletter==letter):
count=count+1
num=num+1
return count
print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1
The Error Message:
Traceback (most recent call last):
File "C:\Users\Charlie Chiang\Desktop\9G.py", line 17, in <module>
print(countLetters("banana", "x"))
File "C:\Users\Charlie Chiang\Desktop\9G.py", line 10, in countLetters
var=word[num]
IndexError: string index out of range
You take it one index too far:
while(num<=wordlen):
num must stay strictly below the length:
while num < wordlen:
because Python sequences are 0-based. A string of length 5 has indices 0, 1, 2, 3, and 4, not 5.
You are reaching one index too far:
while(num<=wordlen):
For a text "a" the len("a") is 1 and last letter can be reached by index 0. Your while condition allows trying index 1, which is not available.
Bonus: counting using Counter
Python stdlib collections provides excellent Counter:
>>> from collections import Counter
>>> Counter("banana").get("x", 0)
0
>>> Counter("banana").get("a", 0)
3
Fixing your code:
def countLetters(word, letter):
count=0
wordlen=len(word)
num=0
wordletter=""
#here, because the index access is 0-based
#you have to test if the num is less than, not less than or equal to length
#last index == len(word) -1
while(num<wordlen):
wordletter=word[num]
if(wordletter==letter):
count=count+1
num=num+1
return count
print(countLetters("banana", "x"))#should print 0
print(countLetters("banana", "a"))#should print 3
print(countLetters("banana", "b"))#should print 1
more elegant way:
str.count method
'banana'.count('x')
'banana'.count('a')
'banana'.count('b')
Because the index of the string starts at zero, the highest valid index will be wordlen-1.
The index start at 0, not 1.
Try changing:
wordletter = word[num-1]

Categories

Resources