使用split函数进行编程有什么问题?

时间:2019-05-07 16:27:07

标签: python split

我想将一行中的字符数限制为77个。结合此限制,如果最后一个单词的长度超过77个字符,我想将其放在当前行下的新行中。

我在下面创建了代码,但将“人”一词放在错误的代码行上。

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)

代码输出为:

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

为什么“人”一词放在第1行而不是第0行?

3 个答案:

答案 0 :(得分:4)

people一词在该文本中出现两次,并且字典只能包含一次给定的键。 people的第二次出现替换了第一次。

答案 1 :(得分:2)

约翰·戈登(John Gordon)告诉您它为什么不起作用的原因。以下内容可能有助于解决您的问题:

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)

答案 2 :(得分:1)

您的人在句子中出现过两次,这就是为什么您看到的第二个“人”的行数= 1。 这是因为python词典不存储重复的键。 这可能会让您更清楚。


如果需要,可以使用列表:

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])