2017-07-28 50 views
1

我只能找到每行的解決方案,但無法找到分頁符;也困惑了很多。對於docx, 也找不到確切的字數。我有一個單詞文檔。我想獲得單詞doc每頁的字數?

function read_doc($filename) { 
$fileHandle = fopen($filename, "r"); 
$line = @fread($fileHandle, filesize($filename)); 
$lines = explode(chr(0x0D), $line); 
$outtext = ""; 
foreach ($lines as $key => $thisline) { 
    if($key > 11){ 
    var_dump($thisline); 
    $pos = strpos($thisline, chr(0x00)); 
    if (($pos !== FALSE) || (strlen($thisline) == 0)) { 
     continue; 
    } else { 
     var_dump($thisline); 
     $text = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\[email protected]\/\_\(\)]/", "", $thisline); 
     var_dump($text); 
    } 
    } 
} 
return $outtext; 

}

+0

我真的需要這種解決方案我累了2天試圖找到這件事情,我會真的很感謝滿,如果有一個人可以幫助我在這裏。 –

+0

您的解決方案有什麼問題?你會得到什麼錯誤?請給我們一些背景。 –

+0

主要問題是我無法找到分頁符,以便我可以在每個頁面中統計單詞,我擁有的是換行符我已經嘗試過規範文件97-2003,但沒有按照那個工作。 –

回答

2

實現自己的代碼這聽起來不像是個好主意。我會推薦使用外部庫,如PHPWord。它應該允許您將文件轉換爲純文本。然後,您可以從中提取字數。

此外,外部庫(例如,增加了對多種文件格式的支持,而不是將您限制爲Word 97-2003)。

+0

phpword當它將其轉換爲文本時確實丟失分頁符 –

+0

解析文檔並在找到分頁符時將其分開。然後,計算單獨的頁面。聽起來很複雜,但我認爲這是針對您的特定問題的最佳解決方案。 –

0

當您解壓縮.doc或.docx文件時,您將獲得文件夾。在word子文件夾中查找document.xml文件。您將使用xml語法獲取整個文檔。按頁面xml語法分割字符串,Strip xml syntax並使用str_word_count

1

這是一個基本的VB.NET代碼,每個頁面計算字數,但要注意它取決於Word認爲是一個字,它不一定是用戶認爲是一個字。根據我的經驗,您需要正確分析Word的行爲方式,它解釋的內容,然後構建邏輯以確保您獲得所需的結果。這不是PHP,但它可以完成這項工作,並且可以成爲您的起點。

Structure WordsPerPage 
    Public pagenum As String 
    Public count As Long 
End Structure 

Public Sub CountWordsPerPage(doc As Document) 
    Dim index As Integer 
    Dim pagenum As Integer 
    Dim newItem As WordsPerPage 
    Dim tmpList As New List(Of WordsPerPage) 

    Try 
     For Each wrd As Range In doc.Words 
      pagenum = wrd.Information(WdInformation.wdActiveEndPageNumber) 
      Debug.Print("Word {0} is on page {1}", wrd.Text, pagenum) 
      index = tmpList.FindIndex(Function(value As WordsPerPage) 
              Return value.pagenum = pagenum 
             End Function) 
      If index <> -1 Then 
       tmpList(index) = New WordsPerPage With {.pagenum = pagenum, .count = tmpList(index).count + 1} 
      Else 
       ' Unique (or first) 
       newItem.count = 1 
       newItem.pagenum = pagenum 
       tmpList.Add(newItem) 
      End If 

     Next 

    Catch ex As Exception 
     WorkerErrorLog.AddLog(ex, Err.Number & " " & Err.Description) 
    Finally 
     Dim totalWordCount As Long = 0 
     For Each item In tmpList 
      totalWordCount = totalWordCount + item.count 
      Debug.Print("Page {0} has {1} words", item.pagenum, item.count) 
     Next 
     Debug.Print("Total word count is {0}", totalWordCount) 
    End Try 
End Sub 
相關問題