python - 继续索引而不是在 Python 中重新开始
问题描述
我有一个问题,我很难找到解决方案。
我需要阅读多个制表符分隔的文档。每个文档中的一列包含表单上的句词索引 (1-1, 1-2,...,1-11, 2-1...) 等。对于我的任务,我需要组合多个文档到 NLP 任务的列表中。这没有问题。但是,这意味着当列表中有新文档时,句子索引自然会从 (1-1) 开始。我希望编写一个继续计算句子的函数,而不管它是一个新文档。
也就是说,而不是例如 (61-10, 61-11, 1-1, 1-2...),我希望有 (61-10, 61-11, 62-1, 62-2.. 。) 等等。单词索引不是那么重要,所以只有句子索引的解决方案就可以了!(即(61、61、62、62,...)。
到目前为止,我已经尝试了一种解决方案,即在列表中隔离句子索引,如下所示,但我不知道如何继续。df
是熊猫df。
sentence = []
for i, ind in enumerate(df["Sectionindex"]):
sent = re.search('(.+?)-\d+', ind)
sentence.append(int(sent.group(1)))
希望我的问题足够清楚,我对python比较陌生。
提前致谢。
解决方案
如果我理解正确,您可以通过计算句点来生成一个句子计数器str.count('\.')
(尽管通过假设每个句点对应一个句子,这确实会过度计算句子)。
然后句子索引将是cumsum()
句子计数器的移位(加1,因为python是0索引)。
玩具示例:
df = pd.DataFrame({'id': [24, 30, 11], 'text': ['this is a sentence. this is another.', 'hello. welcome to stack overflow.', 'this is another sentence.']})
# id text
# 0 24 this is a sentence. this is another.
# 1 30 hello. welcome to stack overflow.
# 2 11 this is another sentence.
df['sentence'] = df['text'].str.count('\.').cumsum().shift(fill_value=0).add(1)
# id text sentence
# 0 24 this is a sentence. this is another. 1
# 1 30 hello. welcome to stack overflow. 3
# 2 11 this is another sentence. 5
推荐阅读
- ios - iPad Pro 第三代发布图片
- python - 计算大型文本文件的词频
- python - 在 python 3.7 中出现无效的语法错误
- amazon-web-services - 如何将 EC2 实例从 aws 迁移到 azure(ubuntu 16.04 实例)
- amazon-web-services - 尝试启动 Jupyter-Notebook 时如何解决错误消息?
- google-cloud-platform - 列出 VM - Google Compute Engine Node.js 客户端库
- android - 在 roomDatabase 中插入时获取自动生成的 id
- php - 更新查询 MySQL PDO 时的情况
- javascript - 流程:`OP` 缺少类型注释
- c# - 如何使相机相对运动