Boognish
Boognish

Reputation: 129

What is wrong with my programming using the split function?

I want to limit the number of characters in a row to 77. In conjunction with this restriction, if the length of the last word will exceed the 77 characters, I would like to place it on a new line below the present line.

I created the code below but it places the words "people" on the wrong line of code.

txt = '''hello there my dear friends and enemies and other people my name is simon and I like to do drawings for all you happy people'''

txtSplit = []
txtSplit = txt.split(' ')

rowsDict = {}
countOfCharactersPerLine = 0
row = 0
for i in range(len(txtSplit)):
    countOfCharactersPerLine += len(txtSplit[i])

    if countOfCharactersPerLine >= CHARACTERS_PER_LINE:
        countOfCharactersPerLine = len(txtSplit[i])
        row += 1
        rowsDict[txtSplit[i]] = row

    else:
        rowsDict[txtSplit[i]] = row 

for key,value in rowsDict.items():
    print(key,value)

The output of the code is:

hello 0
there 0
my 0
dear 0
friends 0
and 0
enemies 0
other 0
people 1
name 0
is 0
simon 0
I 0
like 0
to 0
do 0
drawings 1
for 1
all 1
you 1
happy 1

Why is the word "people" placed on the line 1 instead of line 0?

Upvotes: 0

Views: 62

Answers (3)

Ganesh Jadhav
Ganesh Jadhav

Reputation: 802

You have people occuring twice in your sentence, thats why its the second 'people' that you are seeing that has row count = 1. This is because python dictionaries dont store duplicate keys. This might make you more clear.


If you want it, you can do using lists:

txt = "hello there my dear friends and enemies and other people my name is simon and I like to do drawings for all you happy people"

txtSplit = []
txtSplit = txt.split(' ')
rowsList = []
countOfCharactersPerLine = 0
row = 0
CHARACTERS_PER_LINE = 77
for i in range(len(txtSplit)):
    countOfCharactersPerLine += len(txtSplit[i])
    #print(i,txtSplit[i],len(txtSplit[i]),countOfCharactersPerLine)
    if countOfCharactersPerLine >= CHARACTERS_PER_LINE:
        countOfCharactersPerLine = len(txtSplit[i])
        row += 1
    rowsList.append(txtSplit[i])
    rowsList.append(row)
for i in range(0,len(rowsList),2):
    print(rowsList[i],rowsList[i+1])

Upvotes: 1

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

John Gordon gave you the reason why it doesn't work. The following may be helpful to fix your issue:

word_list = []
countOfCharactersPerLine = 0
row = 0

for s in txtSplit:
    countOfCharactersPerLine += len(s)

    if countOfCharactersPerLine >= CHARACTERS_PER_LINE:
        countOfCharactersPerLine = len(s)
        row += 1
    word_list.append((s, row))

print(word_list)

Upvotes: 2

John Gordon
John Gordon

Reputation: 33335

The word people occurs twice in that text, and dictionaries can only contain a given key once. The second occurrence of people replaces the first.

Upvotes: 4

Related Questions