首页 > 解决方案 > 如何将文本用作字典

问题描述

我已经使用过 docx-python 这个导入让这个docx变成文本。

这是我的代码:

from docx.api import Document

dict = {}

document = Document('test04.docx')
tables = document.tables
for table in tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                print(paragraph.text)

那我想用这个词,所以现在不知道有什么办法。我试图用字典作为一个可以保存这些单词的地方,但它不能。所以我需要别人的帮助。

标签: python-3.x

解决方案


我不完全确定你想要什么。您是否希望整个段落单独包含在列表中?你希望它被单词分割吗?你想让它按字符分割吗?您究竟希望您的文本如何存储在该列表中?一个例子如下:

string = "This is merely a sample string used for this purpose"
print(string.split(' '))

这将返回:

['This', 'is', 'merely', 'a', 'sample', 'string', 'used', 'for', 'this', 'purpose']

string.split() 在所需的输入处拆分。在前面的示例中,我在空格处拆分,但您可以在“。”处拆分。等等

string = "This is a string. This string has sentences. Multiple sentences."
string.split('.')

这给了你:

['This is a string', ' This string has sentences', ' Multiple sentences', '']

正如您在最后一个示例中看到的那样,您在列表中得到一个空项目,因为它在最后一个 '.' 处拆分。也是。

我希望这有点像你所追求的。


推荐阅读