5

小さな問題があります。doc、docx、pptx、ppt、xls、xlsx、odt、pdfを読み取るために、コンソール内の単語を数える必要があります。wc -wまたはgrepは、テキストまたはコンソール出力でのみ機能し、スペースのみをカウントし、日本語、中国語、アラビア数字、ヒンドゥー語、ヘブライ語では異なる区切り文字を使用するため、単語数が間違っているため、これで数えようとしました

pdftotext file.pdf -| wc -w
/usr/local/bin/docx2txt.pl < file.docx | wc -w
/usr/local/bin/pptx2txt.pl < file.pptx | wc -w
antiword file.doc -| wc -w 
antiword file.word -| wc -w

場合によっては、マイクロソフトワード、オープンオフィス悲しい1000ワード、言語が(日本語、中国語、ヒンドゥー教など)の場合、カウンターは10または300ワードを返しますが、通常の文字を使用する場合、最大の間違いは問題ありません。場合によっては、3文字少ない魔女は「OK」です

soffice、openofficeで変換してから、WC -wを試してみましたが、変換すらできません。

soffice --headless --nofirststartwizard --accept=socket,host=127.0.0.1,port=8100; --convert-to pdf some.pdf /var/www/domains/vocabridge.com/devel/temp_files/23/0/东京_1000_words_Docx.docx 

また

 openoffice.org  --headless  --convert-to  ........

また

openoffice.org3 --invisible 

したがって、誰かが正しくカウントする方法や、openofficeなどでドキュメント統計を表示する方法やコンソールでLinuxを表示する方法を知っている場合は、それを共有してください

ありがとう。

4

5 に答える 5

2

Microsoft Word(および明らかにWindows)を使用している場合は、VBAマクロを記述できます。コマンドラインから直接実行する場合は、次のようなVBScriptスクリプトを記述できます。

wordApp = CreateObject("Word.Application")
doc = ... ' open up a Word document using wordApp
docWordCount = doc.Words.Count
' Rinse and repeat...

OpenOffice.org/LibreOfficeがある場合は、同様の(ただしそれ以上の)オプションがあります。Officeアプリにとどまり、マクロを実行したい場合は、おそらくそれを行うことができます。StarBasic APIを十分に理解していないので、その方法を説明できますが、代わりに、コマンドラインから単語数を取得するPythonスクリプトを作成することもできます。大まかに言えば、次のことを行います。

  • 着信ソケット接続を受け入れるための適切なパラメータを使用して、コマンドラインからOOo/LibOのコピーを起動します。http://www.openoffice.org/udk/python/python-bridge.htmlには、その方法についての説明があります。そこに移動し、ブラウザのページ内検索機能を使用して `accept=socket'を検索します

  • OOo / LibO UNOブリッジ(基本的に上記のVBScriptの例と同等)を使用してWord / ODTドキュメントを一度に1つずつ開き、それぞれから単語数を取得するPythonスクリプトを記述します。上記のページはあなたにそれをするための良いスタートを与えるはずです。

  • 単語数は、ドキュメントモデルオブジェクトのWordCountプロパティから取得します:http ://www.openoffice.org/api/docs/common/ref/com/sun/star/text/GenericTextDocument.html#WordCount

于 2013-04-14T07:40:25.660 に答える
1

私は答えが1つのサービスを作成することを見つけました

#!/bin/sh
#
# chkconfig: 345 99 01
#
# description: your script is a test service
#

(while sleep 1; do
  ls pathwithfiles/in | while read file; do
    libreoffice --headless -convert-to pdf "pathwithfiles/in/$file" --outdir pathwithfiles/out
    rm "pathwithfiles/in/$file"
  done
done) &

それから私が必要としたphpスクリプトはすべてを数えました

 $ext = pathinfo($absolute_file_path, PATHINFO_EXTENSION);
        if ($ext !== 'txt' && $ext !== 'pdf') {
            // Convert to pdf
            $tb = mktime() . mt_rand();
            $tempfile = 'locationofpdfs/in/' . $tb . '.' . $ext;
            copy($absolute_file_path, $tempfile);
            $absolute_file_path = 'locationofpdfs/out/' . $tb . '.pdf';
            $ext = 'pdf';
            while (!is_file($absolute_file_path)) sleep(1);
        }
        if ($ext !== 'txt') {
            // Convert to txt
            $tempfile = tempnam(sys_get_temp_dir(), '');
            shell_exec('pdftotext "' . $absolute_file_path . '" ' . $tempfile);
            $absolute_file_path = $tempfile;
            $ext = 'txt';
        }
        if ($ext === 'txt') {
            $seq = '/[\s\.,;:!\? ]+/mu';
            $plain = file_get_contents($absolute_file_path);
            $plain = preg_replace('#\{{{.*?\}}}#su', "", $plain);
            $str = preg_replace($seq, '', $plain);
            $chars = count(preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY));
            $words = count(preg_split($seq, $plain, -1, PREG_SPLIT_NO_EMPTY));
            if ($words === 0) return $chars;
            if ($chars / $words > 10) $words = $chars;
            return $words;
        }
于 2013-04-15T09:47:48.147 に答える
0

wcUnicodeを理解でき、システムのiswspace関数を使用して、Unicode文字が空白であるかどうかを検出します。「iswspace()関数は、wcがプログラムの現在のロケールのクラススペースの文字を表すワイド文字コードであるかどうかをテストします。」したがって、ロケール( )が正しく構成されてwc -wいれば、単語を正しくカウントできるはずです。LC_CTYPE

wcプログラムのソースコード

iswspace機能のマニュアルページ

于 2013-03-10T01:06:39.127 に答える
0

これはあなたが目指していることをするかもしれないと思います

# Continuously updating word count
import unohelper, uno, os, time
from com.sun.star.i18n.WordType import WORD_COUNT
from com.sun.star.i18n import Boundary
from com.sun.star.lang import Locale
from com.sun.star.awt import XTopWindowListener

#socket = True
socket = False
localContext = uno.getComponentContext()

if socket:
    resolver = localContext.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', localContext)
    ctx = resolver.resolve('uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext')
else: ctx = localContext

smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx)

waittime = 1 # seconds

def getWordCountGoal():
    doc = XSCRIPTCONTEXT.getDocument()
    retval = 0

    # Only if the field exists
    if doc.getTextFieldMasters().hasByName('com.sun.star.text.FieldMaster.User.WordCountGoal'):
        # Get the field
        wordcountgoal = doc.getTextFieldMasters().getByName('com.sun.star.text.FieldMaster.User.WordCountGoal')
        retval = wordcountgoal.Content

    return retval

goal = getWordCountGoal()

def setWordCountGoal(goal):
    doc = XSCRIPTCONTEXT.getDocument()

    if doc.getTextFieldMasters().hasByName('com.sun.star.text.FieldMaster.User.WordCountGoal'):
        wordcountgoal = doc.getTextFieldMasters().getByName('com.sun.star.text.FieldMaster.User.WordCountGoal')
        wordcountgoal.Content = goal

    # Refresh the field if inserted in the document from Insert > Fields >
    # Other... > Variables > Userdefined fields
    doc.TextFields.refresh()

def printOut(txt):
    if socket: print txt
    else:
        model = desktop.getCurrentComponent()
        text = model.Text
        cursor = text.createTextCursorByRange(text.getEnd())
        text.insertString(cursor, txt + '\r', 0)

def hotCount(st):
    '''Counts the number of words in a string.

    ARGUMENTS:

    str st: count the number of words in this string

    RETURNS:

    int: the number of words in st'''
    startpos = long()
    nextwd = Boundary()
    lc = Locale()
    lc.Language = 'en'
    numwords = 1
    mystartpos = 1
    brk = smgr.createInstanceWithContext('com.sun.star.i18n.BreakIterator', ctx)
    nextwd = brk.nextWord(st, startpos, lc, WORD_COUNT)
    while nextwd.startPos != nextwd.endPos:
        numwords += 1
        nw = nextwd.startPos
        nextwd = brk.nextWord(st, nw, lc, WORD_COUNT)

    return numwords

def updateCount(wordCountModel, percentModel):
    '''Updates the GUI.
    Updates the word count and the percentage completed in the GUI. If some
    text of more than one word is selected (including in multiple selections by
    holding down the Ctrl/Cmd key), it updates the GUI based on the selection;
    if not, on the whole document.'''

    model = desktop.getCurrentComponent()
    try:
        if not model.supportsService('com.sun.star.text.TextDocument'):
            return
    except AttributeError: return

    sel = model.getCurrentSelection()
    try: selcount = sel.getCount()
    except AttributeError: return

    if selcount == 1 and sel.getByIndex(0).getString == '':
        selcount = 0

    selwords = 0
    for nsel in range(selcount):
        thisrange = sel.getByIndex(nsel)
        atext = thisrange.getString()
        selwords += hotCount(atext)

    if selwords > 1: wc = selwords
    else:
        try: wc = model.WordCount
        except AttributeError: return
    wordCountModel.Label = str(wc)

    if goal != 0:
        pc_text =  100 * (wc / float(goal))
        #pc_text = '(%.2f percent)' % (100 * (wc / float(goal)))
        percentModel.ProgressValue = pc_text
    else:
        percentModel.ProgressValue = 0

# This is the user interface bit. It looks more or less like this:

###############################
# Word Count            _ o x #
###############################
#            _____            #
#     451 /  |500|            #
#            -----            #
# ___________________________ #
# |##############           | #
# --------------------------- #
###############################

# The boxed `500' is the text entry box.

class WindowClosingListener(unohelper.Base, XTopWindowListener):
    def __init__(self):
        global keepGoing

        keepGoing = True
    def windowClosing(self, e):
        global keepGoing

        keepGoing = False
        setWordCountGoal(goal)
        e.Source.setVisible(False)

def addControl(controlType, dlgModel, x, y, width, height, label, name = None):
    control = dlgModel.createInstance(controlType)
    control.PositionX = x
    control.PositionY = y
    control.Width = width
    control.Height = height
    if controlType == 'com.sun.star.awt.UnoControlFixedTextModel':
        control.Label = label
    elif controlType == 'com.sun.star.awt.UnoControlEditModel':
        control.Text = label
    elif controlType == 'com.sun.star.awt.UnoControlProgressBarModel':
        control.ProgressValue = label

    if name:
        control.Name = name
        dlgModel.insertByName(name, control)
    else:
        control.Name = 'unnamed'
        dlgModel.insertByName('unnamed', control)

    return control

def loopTheLoop(goalModel, wordCountModel, percentModel):
    global goal

    while keepGoing:
        try: goal = int(goalModel.Text)
        except: goal = 0
        updateCount(wordCountModel, percentModel)
        time.sleep(waittime)

if not socket:
    import threading
    class UpdaterThread(threading.Thread):
        def __init__(self, goalModel, wordCountModel, percentModel):
            threading.Thread.__init__(self)

            self.goalModel = goalModel
            self.wordCountModel = wordCountModel
            self.percentModel = percentModel

        def run(self):
            loopTheLoop(self.goalModel, self.wordCountModel, self.percentModel)

def wordCount(arg = None):
    '''Displays a continuously updating word count.'''
    dialogModel = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', ctx)

    dialogModel.PositionX = XSCRIPTCONTEXT.getDocument().CurrentController.Frame.ContainerWindow.PosSize.Width / 2.2 - 105
    dialogModel.Width = 100
    dialogModel.Height = 30
    dialogModel.Title = 'Word Count'

    lblWc = addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 2, 25, 14, '', 'lblWc')
    lblWc.Align = 2 # Align right
    addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 33, 2, 10, 14, ' / ')
    txtGoal = addControl('com.sun.star.awt.UnoControlEditModel', dialogModel, 45, 1, 25, 12, '', 'txtGoal')
    txtGoal.Text = goal

    #addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 25, 50, 14, '(percent)', 'lblPercent')

    ProgressBar = addControl('com.sun.star.awt.UnoControlProgressBarModel', dialogModel, 6, 15, 88, 10,'' , 'lblPercent')
    ProgressBar.ProgressValueMin = 0
    ProgressBar.ProgressValueMax =100
    #ProgressBar.Border = 2
    #ProgressBar.BorderColor = 255
    #ProgressBar.FillColor = 255
    #ProgressBar.BackgroundColor = 255

    addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 124, 2, 12, 14, '', 'lblMinus')

    controlContainer = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', ctx)
    controlContainer.setModel(dialogModel)

    controlContainer.addTopWindowListener(WindowClosingListener())
    controlContainer.setVisible(True)
    goalModel = controlContainer.getControl('txtGoal').getModel()
    wordCountModel = controlContainer.getControl('lblWc').getModel()
    percentModel = controlContainer.getControl('lblPercent').getModel()
    ProgressBar.ProgressValue = percentModel.ProgressValue

    if socket:
        loopTheLoop(goalModel, wordCountModel, percentModel)
    else:
        uthread = UpdaterThread(goalModel, wordCountModel, percentModel)
        uthread.start()

keepGoing = True
if socket:
    wordCount()
else:
    g_exportedScripts = wordCount,

詳細についてはリンク

https://superuser.com/questions/529446/running-word-count-in-openoffice-writer

これがトムに関して役立つことを願っています

編集:それから私はこれを見つけました

http://forum.openoffice.org/en/forum/viewtopic.php?f=7&t=22555

于 2013-03-08T13:36:24.383 に答える
0

@Yawarが書いたものに基づいて構築するだけです。コンソールからMSワードで単語数を数える方法のより明確な手順は次のとおりです。

Range.ComputeStatistics(wdStatisticWords)また、Wordsプロパティの代わりに、より正確なものを使用します。詳細については、こちらを参照してください:https ://support.microsoft.com/en-za/help/291447/word-count-appears-inaccurate-when-you-use-the-vba-words-property

  1. と呼ばれるスクリプトを作成wc.vbsし、これをその中に入れます。

    Set word = CreateObject("Word.Application")
    word.Visible = False
    Set doc = word.Documents.Open("<replace with absolute path to your .docx/.pdf>")
    docWordCount = doc.Range.ComputeStatistics(wdStatisticWords)
    word.Quit
    Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
    WScript.Echo docWordCount & " words"
    
  2. wc.vbs保存して実行したディレクトリでPowerShellを開くcscript .\wc.vbsと、単語数が返されます:)

于 2019-10-01T20:03:01.550 に答える