【问题标题】:Word : Deleting Lines in between a Table and a Heading using PythonWord:使用 Python 删除表格和标题之间的行
【发布时间】:2013-04-25 06:45:02
【问题描述】:

我有一个场景,其中有一个像 "Call Tree:" 这样的标题/常量文本出现在整个 Word 文档中,然后有一些行,一旦行结束,有一个表格。所以我希望使用 python/win32 组件删除表格和标题/常量文本 "Call Tree:" 之间的行。

例如:

输入是:

...

Call Tree :

Line 1 ...

Line 2 ...

....

....

....

....

Line N ....

Table # 1

.....

输出为(即删除表格和“调用树”之间的所有行):

...

Call Tree :


Table # 1

.....

我不确定,是否有任何方法可以在常量文本(即“调用树”和表格)之间选择多行。 我知道,可以使用以下方法选择行和删除:

..

    app = win32com.client.DispatchEx("Word.Application")
    app.Visible = 0
    app.DisplayAlerts = 0

    # select a Text
    app.Selection.Find.Execute("TEXT TO BE SELECTED")
    #  extend it to end
    app.Selection.EndKey(Unit=win32com.client.constants.wdLine,Extend=win32com.client.constants.wdExtend)

    # check what has been selected
    app.Selection.Range()

    # and then delete it
    app.Selection.Delete()

..

但我不确定,如何使用这个条件选择多行。

对此有何想法/建议?

【问题讨论】:

    标签: python ms-word pywin32 win32com


    【解决方案1】:

    您可以在使用 MoveRight 和 EndKey 找到文本后遍历行,然后您可以使用属性 Tables 测试所选内容是否为表格。有点像

    import win32com.client as com
    from win32com.client import constants as wcons
    
    app = com.Dispatch('Word.Application')
    # Find the text
    app.Selection.Find.Execute('Call Tree',
            False, False, False, False, False,
            True, wcons.wdFindContinue, False,
            False,False,)
    # Extend the selection to the end
    app.Selection.EndKey(Unit=wcons.wdLine)
    while True:
        # Move the selection to the next character
        app.Selection.MoveRight(Unit=wcons.wdCharacter, Count=1)
        # And Select the whole line
        app.Selection.EndKey(Unit=wcons.wdLine, Extend=wcons.wdExtend)
        # If I hit the table...
        if app.Selection.Tables.Count:
            print "Table found... Stop"
            # I leave the loop
            break
        # Otherwise delete the selection
        print "Deleting ...",app.Selection.Text
        app.Selection.Delete()
        # And delete the return
        app.Selection.TypeBackspace()
    

    我建议先尝试使用宏在 word 中做你想做的事情(如果你不熟悉 VBA,请尝试录制宏),然后将代码转换为 Python。

    【讨论】:

    • 当然......每当我遇到任何问题时,我也在做 Marco 到 Python 的转换,但我自己无法找出上述问题的解决方案......而且,是的你的代码对我帮助很大:) .. 谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多