ホームページ バックエンド開発 Python チュートリアル python3+PyQt5 は、マルチスレッドをサポートするページ インデクサー アプリケーションを実装します。

python3+PyQt5 は、マルチスレッドをサポートするページ インデクサー アプリケーションを実装します。

Apr 20, 2018 pm 02:31 PM
ページ

この記事では、主に python3+PyQt5 がマルチスレッドをサポートするページ インデクサー アプリケーションを実装する方法を詳しく紹介します。興味のある方は参考にしてください。この記事では、Python3+pyqt5 ページ インデクサー アプリケーションの例を使用して Python Qt を実装します。 GUI 高速プログラミングの第 19 章。

/home/yrd/eric_workspace/chap19/walker_ans.py

#!/usr/bin/env python3

import codecs
import html.entities
import re
import sys
from PyQt5.QtCore import (QMutex, QThread,pyqtSignal,Qt)

class Walker(QThread):
 finished = pyqtSignal(bool,int)
 indexed = pyqtSignal(str,int)
 COMMON_WORDS_THRESHOLD = 250
 MIN_WORD_LEN = 3
 MAX_WORD_LEN = 25
 INVALID_FIRST_OR_LAST = frozenset("0123456789_")
 STRIPHTML_RE = re.compile(r"<[^>]*?>", re.IGNORECASE|re.MULTILINE)
 ENTITY_RE = re.compile(r"&(\w+?);|(\d+?);")
 SPLIT_RE = re.compile(r"\W+", re.IGNORECASE|re.MULTILINE)

 def __init__(self, index, lock, files, filenamesForWords,
     commonWords, parent=None):
  super(Walker, self).__init__(parent)
  self.index = index
  self.lock = lock
  self.files = files
  self.filenamesForWords = filenamesForWords
  self.commonWords = commonWords
  self.stopped = False
  self.mutex = QMutex()
  self.completed = False


 def stop(self):
  try:
   self.mutex.lock()
   self.stopped = True
  finally:
   self.mutex.unlock()


 def isStopped(self):
  try:
   self.mutex.lock()
   return self.stopped
  finally:
   self.mutex.unlock()


 def run(self):
  self.processFiles()
  self.stop()
  self.finished.emit(self.completed,self.index)


 def processFiles(self):
  def unichrFromEntity(match):
   text = match.group(match.lastindex)
   if text.isdigit():
    return chr(int(text))
   u = html.entities.name2codepoint.get(text)
   return chr(u) if u is not None else ""

  for fname in self.files:
   if self.isStopped():
    return
   words = set()
   fh = None
   try:
    fh = codecs.open(fname, "r", "UTF8", "ignore")
    text = fh.read()
   except EnvironmentError as e:
    sys.stderr.write("Error: {0}\n".format(e))
    continue
   finally:
    if fh is not None:
     fh.close()
   if self.isStopped():
    return
   text = self.STRIPHTML_RE.sub("", text)
   text = self.ENTITY_RE.sub(unichrFromEntity, text)
   text = text.lower()
   for word in self.SPLIT_RE.split(text):
    if (self.MIN_WORD_LEN <= len(word) <=
     self.MAX_WORD_LEN and
     word[0] not in self.INVALID_FIRST_OR_LAST and
     word[-1] not in self.INVALID_FIRST_OR_LAST):
     try:
      self.lock.lockForRead()
      new = word not in self.commonWords
     finally:
      self.lock.unlock()
     if new:
      words.add(word)
   if self.isStopped():
    return
   for word in words:
    try:
     self.lock.lockForWrite()
     files = self.filenamesForWords[word]
     if len(files) > self.COMMON_WORDS_THRESHOLD:
      del self.filenamesForWords[word]
      self.commonWords.add(word)
     else:
      files.add(str(fname))
    finally:
     self.lock.unlock()
   self.indexed.emit(fname,self.index)
  self.completed = True


/home/yrd/eric_workspace/chap19/pageindexer_ans.pyw

#!/usr/bin/env python3

import collections
import os
import sys
from PyQt5.QtCore import (QDir, QReadWriteLock, QMutex,Qt)
from PyQt5.QtWidgets import (QApplication, QDialog, QFileDialog, QFrame,
        QHBoxLayout, QLCDNumber, QLabel, QLineEdit, QListWidget,
        QPushButton, QVBoxLayout)
import walker_ans as walker


def isAlive(qobj):
 import sip
 try:
  sip.unwrapinstance(qobj)
 except RuntimeError:
  return False
 return True


class Form(QDialog):

 def __init__(self, parent=None):
  super(Form, self).__init__(parent)

  self.mutex = QMutex()
  self.fileCount = 0
  self.filenamesForWords = collections.defaultdict(set)
  self.commonWords = set()
  self.lock = QReadWriteLock()
  self.path = QDir.homePath()
  pathLabel = QLabel("Indexing path:")
  self.pathLabel = QLabel()
  self.pathLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
  self.pathButton = QPushButton("Set &Path...")
  self.pathButton.setAutoDefault(False)
  findLabel = QLabel("&Find word:")
  self.findEdit = QLineEdit()
  findLabel.setBuddy(self.findEdit)
  commonWordsLabel = QLabel("&Common words:")
  self.commonWordsListWidget = QListWidget()
  commonWordsLabel.setBuddy(self.commonWordsListWidget)
  filesLabel = QLabel("Files containing the &word:")
  self.filesListWidget = QListWidget()
  filesLabel.setBuddy(self.filesListWidget)
  filesIndexedLabel = QLabel("Files indexed")
  self.filesIndexedLCD = QLCDNumber()
  self.filesIndexedLCD.setSegmentStyle(QLCDNumber.Flat)
  wordsIndexedLabel = QLabel("Words indexed")
  self.wordsIndexedLCD = QLCDNumber()
  self.wordsIndexedLCD.setSegmentStyle(QLCDNumber.Flat)
  commonWordsLCDLabel = QLabel("Common words")
  self.commonWordsLCD = QLCDNumber()
  self.commonWordsLCD.setSegmentStyle(QLCDNumber.Flat)
  self.statusLabel = QLabel("Click the &#39;Set Path&#39; "
         "button to start indexing")
  self.statusLabel.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)

  topLayout = QHBoxLayout()
  topLayout.addWidget(pathLabel)
  topLayout.addWidget(self.pathLabel, 1)
  topLayout.addWidget(self.pathButton)
  topLayout.addWidget(findLabel)
  topLayout.addWidget(self.findEdit, 1)
  leftLayout = QVBoxLayout()
  leftLayout.addWidget(filesLabel)
  leftLayout.addWidget(self.filesListWidget)
  rightLayout = QVBoxLayout()
  rightLayout.addWidget(commonWordsLabel)
  rightLayout.addWidget(self.commonWordsListWidget)
  middleLayout = QHBoxLayout()
  middleLayout.addLayout(leftLayout, 1)
  middleLayout.addLayout(rightLayout)
  bottomLayout = QHBoxLayout()
  bottomLayout.addWidget(filesIndexedLabel)
  bottomLayout.addWidget(self.filesIndexedLCD)
  bottomLayout.addWidget(wordsIndexedLabel)
  bottomLayout.addWidget(self.wordsIndexedLCD)
  bottomLayout.addWidget(commonWordsLCDLabel)
  bottomLayout.addWidget(self.commonWordsLCD)
  bottomLayout.addStretch()
  layout = QVBoxLayout()
  layout.addLayout(topLayout)
  layout.addLayout(middleLayout)
  layout.addLayout(bottomLayout)
  layout.addWidget(self.statusLabel)
  self.setLayout(layout)

  self.walkers = []
  self.completed = []
  self.pathButton.clicked.connect(self.setPath)
  self.findEdit.returnPressed.connect(self.find)
  self.setWindowTitle("Page Indexer")


 def stopWalkers(self):
  for walker in self.walkers:
   if isAlive(walker) and walker.isRunning():
    walker.stop()
  for walker in self.walkers:
   if isAlive(walker) and walker.isRunning():
    walker.wait()
  self.walkers = []
  self.completed = []


 def setPath(self):
  self.stopWalkers()
  self.pathButton.setEnabled(False)
  path = QFileDialog.getExistingDirectory(self,
     "Choose a Path to Index", self.path)
  if not path:
   self.statusLabel.setText("Click the &#39;Set Path&#39; "
          "button to start indexing")
   self.pathButton.setEnabled(True)
   return
  self.statusLabel.setText("Scanning directories...")
  QApplication.processEvents() # Needed for Windows
  self.path = QDir.toNativeSeparators(path)
  self.findEdit.setFocus()
  self.pathLabel.setText(self.path)
  self.statusLabel.clear()
  self.filesListWidget.clear()
  self.fileCount = 0
  self.filenamesForWords = collections.defaultdict(set)
  self.commonWords = set()
  nofilesfound = True
  files = []
  index = 0
  for root, dirs, fnames in os.walk(str(self.path)):
   for name in [name for name in fnames
       if name.endswith((".htm", ".html"))]:
    files.append(os.path.join(root, name))
    if len(files) == 1000:
     self.processFiles(index, files[:])
     files = []
     index += 1
     nofilesfound = False
  if files:
   self.processFiles(index, files[:])
   nofilesfound = False
  if nofilesfound:
   self.finishedIndexing()
   self.statusLabel.setText(
     "No HTML files found in the given path")


 def processFiles(self, index, files):
  thread = walker.Walker(index, self.lock, files,
    self.filenamesForWords, self.commonWords, self)
  thread.indexed[str,int].connect(self.indexed)
  thread.finished[bool,int].connect(self.finished)
  thread.finished.connect(thread.deleteLater)
  self.walkers.append(thread)
  self.completed.append(False)
  thread.start()
  thread.wait(300) # Needed for Windows


 def find(self):
  word = str(self.findEdit.text())
  if not word:
   try:
    self.mutex.lock()
    self.statusLabel.setText("Enter a word to find in files")
   finally:
    self.mutex.unlock()
   return
  try:
   self.mutex.lock()
   self.statusLabel.clear()
   self.filesListWidget.clear()
  finally:
   self.mutex.unlock()
  word = word.lower()
  if " " in word:
   word = word.split()[0]
  try:
   self.lock.lockForRead()
   found = word in self.commonWords
  finally:
   self.lock.unlock()
  if found:
   try:
    self.mutex.lock()
    self.statusLabel.setText("Common words like &#39;{0}&#39; "
      "are not indexed".format(word))
   finally:
    self.mutex.unlock()
   return
  try:
   self.lock.lockForRead()
   files = self.filenamesForWords.get(word, set()).copy()
  finally:
   self.lock.unlock()
  if not files:
   try:
    self.mutex.lock()
    self.statusLabel.setText("No indexed file contains "
      "the word &#39;{0}&#39;".format(word))
   finally:
    self.mutex.unlock()
   return
  files = [QDir.toNativeSeparators(name) for name in
     sorted(files, key=str.lower)]
  try:
   self.mutex.lock()
   self.filesListWidget.addItems(files)
   self.statusLabel.setText(
     "{0} indexed files contain the word &#39;{1}&#39;".format(
     len(files), word))
  finally:
   self.mutex.unlock()


 def indexed(self, fname, index):
  try:
   self.mutex.lock()
   self.statusLabel.setText(fname)
   self.fileCount += 1
   count = self.fileCount
  finally:
   self.mutex.unlock()
  if count % 25 == 0:
   try:
    self.lock.lockForRead()
    indexedWordCount = len(self.filenamesForWords)
    commonWordCount = len(self.commonWords)
   finally:
    self.lock.unlock()
   try:
    self.mutex.lock()
    self.filesIndexedLCD.display(count)
    self.wordsIndexedLCD.display(indexedWordCount)
    self.commonWordsLCD.display(commonWordCount)
   finally:
    self.mutex.unlock()
  elif count % 101 == 0:
   try:
    self.lock.lockForRead()
    words = self.commonWords.copy()
   finally:
    self.lock.unlock()
   try:
    self.mutex.lock()
    self.commonWordsListWidget.clear()
    self.commonWordsListWidget.addItems(sorted(words))
   finally:
    self.mutex.unlock()


 def finished(self, completed, index):
  done = False
  if self.walkers:
   self.completed[index] = True
   if all(self.completed):
    try:
     self.mutex.lock()
     self.statusLabel.setText("Finished")
     done = True
    finally:
     self.mutex.unlock()
  else:
   try:
    self.mutex.lock()
    self.statusLabel.setText("Finished")
    done = True
   finally:
    self.mutex.unlock()
  if done:
   self.finishedIndexing()


 def reject(self):
  if not all(self.completed):
   self.stopWalkers()
   self.finishedIndexing()
  else:
   self.accept()


 def closeEvent(self, event=None):
  self.stopWalkers()


 def finishedIndexing(self):
  self.filesIndexedLCD.display(self.fileCount)
  self.wordsIndexedLCD.display(len(self.filenamesForWords))
  self.commonWordsLCD.display(len(self.commonWords))
  self.pathButton.setEnabled(True)
  QApplication.processEvents() # Needed for Windows


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
ログイン後にコピー

実行結果:

関連する推奨事項:

スタックされたウィジェットを実装するための python3+PyQt5+Qt デザイナーs

python3 +PyQt5+Qt デザイナーは拡張ダイアログ ボックスを実装します

以上がpython3+PyQt5 は、マルチスレッドをサポートするページ インデクサー アプリケーションを実装します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

Wordでページをコピーする方法 Wordでページをコピーする方法 Feb 20, 2024 am 10:09 AM

Microsoft Word でページをコピーし、書式設定をそのまま維持したいですか? Word でページを複製すると、特定の文書レイアウトまたは形式のコピーを複数作成する場合に時間の節約に役立つため、これは賢明なアイデアです。このガイドでは、テンプレートを作成する場合でも、文書内の特定のページをコピーする場合でも、Word でページをコピーする手順を段階的に説明します。これらの簡単な手順は、最初から始めなくてもページを簡単に再作成できるように設計されています。 Microsoft Word でページをコピーする必要があるのですか? Word でページをコピーすることが非常に有益である理由はいくつかあります。 特定のレイアウトまたは形式の文書をコピーしたい場合。ページ全体を最初から再作成するのとは異なります

8コア16スレッドとはどういう意味ですか? 8コア16スレッドとはどういう意味ですか? Feb 02, 2023 am 11:26 AM

8 コアは、CPU に 8 つの物理コアがあることを意味し、16 スレッドは、CPU が同時にタスクを処理できる最大 16 のスレッドを持つことができることを意味します。コアとスレッドの数は、コンピュータ CPU の重要なパフォーマンス指標です。CPU のコア数が多いほど、処理速度は高くなります。スレッドの数が多いほど、複数のプログラムを同時に実行しやすくなります。スレッドの数は、ある瞬間に CPU が同時に実行できる数、つまり並列処理されるタスクの数に相当するためです。マルチスレッドにより、広範囲にわたる問題の順序が狂ったスーパースカラー処理を最大化し、プロセッサ コンピューティング コンポーネントの利用率を向上させ、データ相関やキャッシュ ミスによって引き起こされるメモリ アクセスの遅延を軽減できます。

iPhone のスタンバイ モードをカスタマイズおよび編集する方法: iOS 17 の新機能 iPhone のスタンバイ モードをカスタマイズおよび編集する方法: iOS 17 の新機能 Sep 21, 2023 pm 04:01 PM

スタンバイは iOS 17 アップデートの新機能で、携帯電話がアイドル状態のときにすぐに情報にアクセスするための新しく強化された方法を提供します。 StandBy を使用すると、時間を確認したり、今後のイベントを表示したり、カレンダーを参照したり、現在地の天気予報の最新情報を入手したりすることができます。起動すると、充電中に横向きに設定すると、iPhone が直感的にスタンバイ モードに入ります。この機能は、ベッドサイドテーブルなどのワイヤレス充電ポイント、または日常業務中に iPhone の充電から離れているときに最適です。スタンバイ中に表示されるさまざまなウィジェットをスワイプすることで、さまざまなアプリのさまざまな情報にアクセスできます。ただし、好みや頻繁に必要な情報に基づいて、これらのウィジェットを変更したり、一部を削除したりすることもできます。それでは、詳しく見ていきましょう

Web ページをすばやく更新するにはどうすればよいですか? Web ページをすばやく更新するにはどうすればよいですか? Feb 18, 2024 pm 01:14 PM

ネットワークを日常的に使用する中でページの更新は頻繁に行われますが、Web ページにアクセスすると、Web ページが読み込まれない、表示が異常になるなどの問題が発生することがあります。現時点では、通常、問題を解決するためにページを更新することを選択しますが、ページを素早く更新するにはどうすればよいでしょうか?ページ更新のショートカット キーについて説明します。ページ更新ショートカットキーは、キーボード操作で現在のWebページを素早く更新する方法です。オペレーティング システムやブラウザが異なると、ページを更新するためのショートカット キーが異なる場合があります。以下では一般的な W を使用します。

iPhoneのホーム画面ページを並べ替え、無効化、削除する方法 iPhoneのホーム画面ページを並べ替え、無効化、削除する方法 Nov 29, 2023 am 08:22 AM

iOS では、Apple は iPhone の個々のホーム画面ページを無効にすることを許可しています。ホーム画面のページを無効にするだけでなく、ホーム画面のページの順序を並べ替えたり、ページを直接削除したりすることもできます。仕組みは次のとおりです。ホーム画面のページを並べ替える方法 ホーム画面でスペースをタッチしたままにして、ジッター モードに入ります。ホーム画面ページを表す点の列をタップします。表示されるホーム画面のグリッドで、ページをタッチしてドラッグし、他のページとの相対的な位置を再配置します。ドラッグに応じて他のものも動きます。新しい配置に満足したら、画面の右上隅にある「完了」をタップし、もう一度「完了」をタップしてディザモードを終了します。ホーム画面ページを無効化または削除する方法 ホーム画面でスペースを押したままにして、ディザ モードに入ります。タップしてホーム画面を表示します

3 秒でページジャンプを実装する方法: PHP プログラミングガイド 3 秒でページジャンプを実装する方法: PHP プログラミングガイド Mar 25, 2024 am 10:42 AM

タイトル: 3秒でできるページジャンプの実装方法: PHPプログラミングガイド Web開発においてページジャンプは一般的な操作ですが、通常はHTMLやJavaScriptのメソッド内のメタタグを使ってページにジャンプします。ただし、特定のケースでは、サーバー側でページ ジャンプを実行する必要があります。この記事では、PHPプログラミングを使用して、3秒以内に指定したページに自動でジャンプする機能を実装する方法と、具体的なコード例を紹介します。 PHP を使用したページジャンプの基本原理 PHP は一種の

LaravelページでCSSが正しく表示されない場合の対処方法 LaravelページでCSSが正しく表示されない場合の対処方法 Mar 10, 2024 am 11:33 AM

「CSS を正しく表示できない Laravel ページを処理する方法、特定のコード例が必要」 Laravel フレームワークを使用して Web アプリケーションを開発する場合、ページで CSS スタイルを正しく表示できず、ページのレンダリングが異常になるという問題が発生することがあります。スタイル。ユーザー エクスペリエンスに影響します。この記事では、Laravel ページで CSS が正しく表示されない場合に対処するいくつかの方法を紹介し、開発者がこの一般的な問題を解決するのに役立つ具体的なコード例を示します。 1. ファイルパスを確認する まずCSSファイルのパスを確認します。

C++ 同時プログラミング: スレッドの枯渇と優先順位の逆転を回避するには? C++ 同時プログラミング: スレッドの枯渇と優先順位の逆転を回避するには? May 06, 2024 pm 05:27 PM

スレッドの枯渇を回避するには、公平なロックを使用してリソースの公平な割り当てを確保するか、スレッドの優先順位を設定します。優先順位の逆転を解決するには、リソースを保持しているスレッドの優先順位を一時的に高める優先順位の継承を使用するか、リソースを必要とするスレッドの優先順位を高めるロック プロモーションを使用します。

See all articles