Python通过将字符串拆分为列表并分隔元素来计算字符串的长度

2024-04-26 20:56:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是在包含分号的文本中查找句子,并查找分号前后的单词数。我知道如何用分号来分割所有的东西,但是我得到了两个字符串,但是我似乎无法计算字符串中的单词?你知道吗

文本如下所示:

"What does Bessie say I have done?" I asked.
"Jane, I don't like cavillers or questioners; besides, there is something truly forbidding in a child taking up her elders in that manner.
Be seated somewhere; and until you can speak pleasantly, remain silent."  
A breakfast-room adjoined the drawing-room, I slipped in there.
It contained a bookcase: I soon possessed myself of a volume, taking care that it should be one stored with pictures.
I mounted into the window- seat: gathering up my feet, I sat cross-legged, like a Turk; and, having drawn the red moreen curtain nearly close, I was shrined in double retirement.
Folds of scarlet drapery shut in my view to the right hand; to the left were the clear panes of glass, protecting, but not separating me from the drear November day.
At intervals, while turning over the leaves of my book, I studied the aspect of that winter afternoon.
Afar, it offered a pale blank of mist and cloud; near a scene of wet lawn and storm-beat shrub, with ceaseless rain sweeping away wildly before a long and lamentable blast.
I returned to my book--Bewick's History of British Birds: the letterpress thereof I cared little for, generally speaking; and yet there were certain introductory pages that, child as I was, I could not pass quite as a blank.
They were those which treat of the haunts of sea-fowl; of "the solitary rocks and promontories" by them only inhabited of the coast of Norway, studded with isles from its southern extremity, the Lindeness, or Naze, to the North Cape--     "Where the Northern Ocean, in vast whirls,    
Boils round the naked, melancholy isles
Of farthest Thule; and the Atlantic surge
Pours in among the stormy Hebrides."
Nor could I pass unnoticed the suggestion of the bleak shores of Lapland, Siberia, Spitzbergen, Nova Zembla, Iceland, Greenland, with "the vast sweep of the Arctic Zone, and those forlorn regions of dreary space,--that reservoir of frost and snow, where firm fields of ice, the accumulation of centuries of winters, glazed in Alpine heights above heights, surround the pole, and concentre the multiplied rigours of extreme cold."  
Of these death-white realms I formed an idea of my own: shadowy, like all the half-comprehended notions that float dim through children's brains, but strangely impressive.

到目前为止,我已经取得了:

count = -1
for line in open("jane_eyre_sentences.txt"):
  words = line.strip("\n")
  count += 1
  if ";" in words:
    wordssplit = words.split(";")


    print("Line " +str(count)+ ":", wordssplit )

我之所以使用计数,是因为每次迭代后计数都会增加1,所以句子会被标记。我去掉了句子末尾的段落,如果句子中有分号,我也用分号把它们分开。你知道吗

到目前为止,我只尝试打印单词split,看看它会给我什么。你知道吗

Line 1: ['"Jane, I don\'t like cavillers or questioners', ' besides, there is something truly forbidding in a child taking up her elders in that manner.']
Line 2: ['Be seated somewhere', ' and until you can speak pleasantly, remain silent."  ']
Line 5: ['I mounted into the window- seat: gathering up my feet, I sat cross-legged, like a Turk', ' and, having drawn the red moreen curtain nearly close, I was shrined in double retirement.']
Line 6: ['Folds of scarlet drapery shut in my view to the right hand', ' to the left were the clear panes of glass, protecting, but not separating me from the drear November day.']
Line 8: ['Afar, it offered a pale blank of mist and cloud', ' near a scene of wet lawn and storm-beat shrub, with ceaseless rain sweeping away wildly before a long and lamentable blast.']
Line 9: ["I returned to my book--Bewick's History of British Birds: the letterpress thereof I cared little for, generally speaking", ' and yet there were certain introductory pages that, child as I was, I could not pass quite as a blank.']
Line 10: ['They were those which treat of the haunts of sea-fowl', ' of "the solitary rocks and promontories" by them only inhabited of the coast of Norway, studded with isles from its southern extremity, the Lindeness, or Naze, to the North Cape--     "Where the Northern Ocean, in vast whirls,    ']
Line 12: ['Of farthest Thule', ' and the Atlantic surge']

Tags: orandofthetoinchildthat
1条回答
网友
1楼 · 发布于 2024-04-26 20:56:19

我不知道你的目的是什么,但据我所知,你只想在一个文件的每一行中,在半字节的左边和右边写上单词的数目?对的?如果是这样的话,这应该对你有用。你知道吗

with open(textfile,'rt',encoding='utf-8')as infile:
    for line in infile:
        for i,e in enumerate(line.split(' ')):
            if e.endswith(';'):
                print(" > {}\nContains {} words to the left, and {} words to the right\n".format(line.strip(),i+1,len(line.strip().split(" "))-(i+1)))

相关问题 更多 >