使用win32com计算单词数

时间:2018-04-06 09:14:45

标签: python pywin32

我在ms word文档中添加了一些文本。然后我想计算单词的数量。怎么做?我的代码如下:

import win32com.client as win32
from time import sleep

word = win32.gencache.EnsureDispatch('Word.Application')

doc = word.Documents.Add()
word.Visible = True
sleep(1)

rng = doc.Range(0,0)
rng.InsertAfter('Can you tell me how many words are there in this sentence?')

2 个答案:

答案 0 :(得分:0)

import win32com.client as win32
from time import sleep

word = win32.gencache.EnsureDispatch('Word.Application')

doc = word.Documents.Add()
word.Visible = True
sleep(1)

stri = 'Can you tell me how many words are there in this sentence?'
num = len([i for i in stri.split(" ")])

rng = doc.Range(0,0)
rng.InsertAfter(stri)

print("number of words : "+str(num))

答案 1 :(得分:0)

使用以下代码,您可以将剪贴板中的字符串粘贴到WORD。最后,您将获得字符串的剪贴板结果:

import win32com.client as win32
import win32api

shell = win32.Dispatch("WScript.Shell")
if shell.AppActivate('word') == False:
    word = win32.gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Add()
    word.Visible = True
    shell.AppActivate('word')


shell.SendKeys("^{a}{BACKSPACE} ")
win32api.Sleep(500)
shell.SendKeys("^v")
shell.SendKeys("%{n}")
shell.SendKeys("{q}")
shell.SendKeys("{f}")
shell.SendKeys("numwords")
shell.SendKeys("~")
shell.SendKeys("^a^c")