【问题标题】:the first line has 5 words , the second line has 4 words and third line has 2 words. So how can i count them using python [closed]第一行 5 个单词,第二行 4 个单词,第三行 2 个单词。那么我如何使用python计算它们[关闭]
【发布时间】:2018-10-30 21:06:37
【问题描述】:

示例:

dam | luru | Goal | Limaste | Querto
elh | Dub | Lon row | Mumb
lhi | mba

我想计算每一行的字符数。例如。第一行有 5 个字符。 请帮忙。

【问题讨论】:

  • 请澄清您的问题:在标题中您要求“用空间替换管道”;在问题正文中,您要求“计算字符”。另外第一行如何包含5个字符,你能举个例子你的意思吗?
  • 第一行是:dam |鲁鲁 |目标 |利马斯特 | Querto 所以有 5 个词,即 dam,luru,Goal,Limaste,Querto。所以我想知道如何使用 R 或 python 来计算它们。

标签: python spyder


【解决方案1】:

如果要删除管道并在 Python 中将其替换为空格:

string = "dam | luru | Goal | Limaste | Querto elh | Dub | Lon row | Mumb lhi | mba"
string.replace('|',' ')

如果要统计字符数(在python中):

string = "dam | luru | Goal | Limaste | Querto elh | Dub | Lon row | Mumb lhi | mba"
parts = string.split('|')
for part in parts:
    print(len(part)+1) #+1 because the | character itself will be removed

编辑:

根据最近的编辑,当存在多行输入时,您希望计算每行中管道分隔项的数量。要为一行做到这一点,您只需执行以下操作:

parts = line.split('|')
print(len(parts))

其中 line 变量包含一行输入。

【讨论】:

  • 这是我得到的错误。Traceback(最近一次调用最后一次):文件“”,第 1 行,在 中 AttributeError:'list' 对象没有属性'head'
  • 坝 |鲁鲁 |目标 |利马斯特 | Querto - 5 elh |配音 |长排 |麻木 - 4 lhi | mba - 1 这是我想要的输出。如你所见大坝|鲁鲁 |目标 |利马斯特 | Querto 是 5 个单词,所以我希望输出为 5。
猜你喜欢
  • 1970-01-01
  • 2022-11-03
  • 2017-02-26
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
相关资源
最近更新 更多