我想把一行的字符数限制为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行?你知道吗
你的句子中出现了两次人物,这就是为什么你看到的第二个“人物”的行数为1。 这是因为python字典不存储重复的键。 这可能会让你更清楚。
如果需要,可以使用列表:
单词
people
在该文本中出现两次,字典只能包含一次给定的键。第二次出现的people
替换了第一次出现的。你知道吗约翰·戈登给了你它不起作用的原因。以下内容可能有助于解决您的问题:
相关问题 更多 >
编程相关推荐