【问题标题】:Python : Slice each sentence in list of sentencesPython:在句子列表中切片每个句子
【发布时间】:2017-10-12 14:14:21
【问题描述】:

我试图从 [0:10] 字符的句子列表中分割每个句子。

句子列表示例:list name = sd_list

['我在德里出生长大。',

'我从 2012 年开始使用戴尔 Latitude E5140 笔记本电脑。',

'我从 2014 年开始在 ABC 公司工作。']

我尝试通过运行以下代码来分割每个句子的前 10 个字符,但失败了。

sent10 = [s[0:10] for s in sd_list]

通过运行这个我遇到了下面的TypeError


TypeError Traceback(最近一次调用最后一次) 在 () ----> 1 [s[0:10] for s in sd_list]

在 (.0) ----> 1 [s[0:10] for s in sd_list]

TypeError: 'float' 对象不可下标


--> 我什至尝试定义一个函数:

def sent_slice(text):

     for s in range(0,len(text)):

        text[s] = text[s][0:10]

     return text

sent_slice(sd_list)

TypeError Traceback(最近一次调用最后一次) 在 () ----> 1 个 sent_slice(sd_list)

在 sent_slice(text) 1 def sent_slice(文本): 2 for s in range(0,len(text)): ----> 3 文本[s] = 文本[s][0:10] 4 返回文本

TypeError: 'float' 对象不可下标


谁能帮我理解这个“TypeError: 'float' object is not subscriptable”。如何实现我的句子切片目标?

【问题讨论】:

  • 您能告诉我们 sd_list 中的确切内容吗?
  • 您的第一次尝试是正确的。您可以打印并查看 sd_list 变量中存储的内容吗?
  • 还有更多内容。请发布完整、准确的代码。
  • sd_list 包含大约 10 万个以上的元素。有一些空白行导致了问题。能够解决。

标签: python text-analysis


【解决方案1】:

这意味着您在sd_list 中有一个float。您可以通过以下方式找到它:

print([f for f in sd_list if isinstance(f, float)])

【讨论】:

  • 它工作并且能够整理列表中导致问题的空白/nan记录。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
  • 2018-08-17
相关资源
最近更新 更多