[PYTHON] J'ai créé une fonction qui divise assez bien une copie maladroite d'un texte PDF.

introduction

À l'origine deux fois auparavant, l'article précédent [Python] Traduisons automatiquement le PDF anglais (mais sans s'y limiter) avec la traduction DeepL ou Google pour en faire un fichier texte. Suite [Python] Traduisons automatiquement le PDF anglais (mais sans s'y limiter) avec la traduction DeepL ou Google dans un fichier texte, pas de HTML.

Je l'ai écrit pour une utilisation dans, mais cela semble utile, je vais donc le présenter séparément.

Problèmes avec le texte copié à partir d'un PDF

Je n'ai pas de connaissances détaillées sur le PDF, Il semble que le texte est divisé en petites parties et écrit dans le PDF, et le texte copié contient également le code de saut de ligne à la position affichée dans le PDF.

Par exemple, en PDF

ABC.\\\DFE.\\\GHI.

Dans le cas d'un affichage comme, le texte copié est

ABC.{\r\n}DEF.{\r\n}GHI.

Etc. (L'exemple ci-dessus est pour Windows)

Ensuite, j'ai pensé que je devais effacer le code de saut de ligne et relier les phrases.

ABC.DEF.GHI.

De cette façon, dans cet exemple, il y a un point pour que chaque phrase ne soit pas mélangée.


Cependant, ce n'est pas une histoire si simple de tout résoudre avec cela.

Qu'en est-il des cas suivants?

1. Introduction\\\ABCDEF.\\\GHIJKL.\\\MNOPQR.

Si vous effacez simplement le code de saut de ligne,

1. IntroductionABCDEF.GHIJKL.MNOPQR.

Il est devenu impossible de faire la distinction entre la première ligne et la deuxième ligne sans point.

Donc le problème est ** Les parties qui n'ont pas toujours de marques de rupture telles que des points, comme des en-têtes, Comment déduire et décomposer du texte copié qui ne contient que des phrases et des codes de saut de ligne. ** ** C'est le but.

Ce que j'ai fait

  1. Diviser par code de saut de ligne
  2. Effacer les lignes vides
  3. Devinez s'il s'agit du texte ou du titre à partir de la différence du nombre de caractères entre la phrase divisée qui vous intéresse et la phrase suivante.
  4. Jugez si le premier caractère de la phrase suivante est inférieur
  5. Si toutes les lettres majuscules sont utilisées, il est considéré comme une phrase d'en-tête.
  6. Si un nombre (chiffre arabe, chiffre romain) +. (Point) se trouve dans l'en-tête, il est considéré comme une phrase d'en-tête.
  7. Même s'il existe une grande différence dans le nombre de caractères entre la phrase qui vous intéresse et la phrase suivante, si la phrase suivante est plus courte et comporte un point (ou une ponctuation), elle est jugée comme une phrase continue.
  8. Juger comme des phrases continues à moins que les parenthèses ne soient fermées.

Nous avons adopté une méthode telle que. C'est assez simple, mais la plupart des phrases

・ Cap ・ Paragraphe · Phrase

Vous avez maintenant une fonction qui peut être divisée en n'importe quelle unité.

code

import re

def textParser(text, n=30, braketDetect=True):
    text = text.splitlines()
    sentences = []
    t = ""
    bra_cnt, ket_cnt = 0, 0
    for i in range(len(text)):
        if not bool(re.search("\S", text[i])): continue
        if braketDetect:
            bra_cnt += len(re.findall("[\(?]", text[i]))
            ket_cnt += len(re.findall("[\)?]", text[i]))
        if i != len(text) - 1:
            if bool(re.fullmatch(r"[A-Z\s]+", text[i])):
                if t != "": sentences.append(t)
                t = ""
                sentences.append(text[i])
            elif text[i + 1] == "" or re.match(
                    "(\d{1,2}[\.,?]\s?|I{1,3}V{0,1}X{0,1}[\.,?]|V{0,1}X{0,1}I{1,3}[\.,?])+\s",
                    text[i]):
                sentences.append(t + text[i])
                t = ""
            elif (text[i][-1] not in ("?", ".", "?") and
                  (abs(len(text[i]) - len(text[i + 1])) < n or
                   (len(t + text[i]) > len(text[i + 1]) and
                    (text[i + 1][-1] in ("?", ".", "?")
                     or bool(re.match("[A-Z]", text[i + 1][0])))))) or bool(
                         re.match("[a-z]|\)",
                                  text[i + 1][0])) or bra_cnt > ket_cnt:
                t += " " + text[i]
            else:
                sentences.append(t + text[i])
                t = ""
        else:
            sentences.append(text[i])
    return sentences

Si le résultat n'est pas bon, essayez d'ajuster la valeur de «n» (surtout en japonais, environ 15 à 20 peuvent être bons). Si, pour une raison quelconque, le nombre de parenthèses n'est pas aligné et que le texte est étrangement figé, définissez braketDetect sur False.

J'ai essayé de l'utiliser

Python 3.8.5 Documentation PDF (format papier US-Letter) \ tutorial.pdf À partir de la page numéro 5 (p.11)

Une copie de l'original

CHAPTER
TWO
USING THE PYTHON INTERPRETER
2.1 Invoking the Interpreter
The Python interpreter is usually installed as /usr/local/bin/python3.8 on those machines where it is available;
putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:
python3.8
to the shell.1 Since the choice of the directory where the interpreter lives is an installation option, other places are possible;
check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative
location.)
On Windows machines where you have installed Python from the Microsoft Store, the python3.8 command will be
available. If you have the py.exe launcher installed, you can use the py command. See setting-envvars for other ways to
launch Python.
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the
interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command:
quit().
The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that
support the GNU Readline library. Perhaps the quickest check to see whether command line editing is supported is typing
Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive
Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed,
command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads
and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and
executes a script from that file.
A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) in
command, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are
special to the shell, it is usually advised to quote command in its entirety with single quotes.
Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ...,
which executes the source file for module as if you had spelled out its full name on the command line.
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This
can be done by passing -i before the script.
All command line options are described in using-on-general.
1 On Unix, the Python 3.x interpreter is by default not installed with the executable named python, so that it does not conflict with a simultaneously
installed Python 2.x executable.

Il y a un code de saut de ligne à la fin de chaque ligne. Si vous affichez "comme code de saut de ligne" pour une meilleure compréhension

CHAPTER\r\nTWO\r\nUSING THE PYTHON INTERPRETER\r\n2.1 Invoking the Interpreter\r\nThe Python interpreter is usually installed as /usr/local/bin/python3.8 on those machines where it is available;\r\nputting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:\r\npython3.8\r\nto the shell.1 Since the choice of the directory where the interpreter lives is an installation option, other places are possible;\r\ncheck with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative\r\nlocation.)\r\nOn Windows machines where you have installed Python from the Microsoft Store, the python3.8 command will be\r\navailable. If you have the py.exe launcher installed, you can use the py command. See setting-envvars for other ways to\r\nlaunch Python.\r\nTyping an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the\r\ninterpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command:\r\nquit().\r\nThe interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that\r\nsupport the GNU Readline library. Perhaps the quickest check to see whether command line editing is supported is typing\r\nControl-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive\r\nInput Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed,\r\ncommand line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.\r\nThe interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads\r\nand executes commands interactively; when called with a file name argument or with a file as standard input, it reads and\r\nexecutes a script from that file.\r\nA second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) in\r\ncommand, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are\r\nspecial to the shell, it is usually advised to quote command in its entirety with single quotes.\r\nSome Python modules are also useful as scripts. These can be invoked using python -m module [arg] ...,\r\nwhich executes the source file for module as if you had spelled out its full name on the command line.\r\nWhen a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This\r\ncan be done by passing -i before the script.\r\nAll command line options are described in using-on-general.\r\n1 On Unix, the Python 3.x interpreter is by default not installed with the executable named python, so that it does not conflict with a simultaneously\r\ninstalled Python 2.x executable.

Ça ressemble à ça.

Je vais le jeter dans la fonction que j'ai créée cette fois. En supposant que la phrase ci-dessus est copiée dans le presse-papiers

from pyperclip import paste #Fonction pour obtenir la valeur (texte) du presse-papiers

print("\n".join(textParser(paste())))

out


CHAPTER
TWO
USING THE PYTHON INTERPRETER
2.1 Invoking the Interpreter
The Python interpreter is usually installed as /usr/local/bin/python3.8 on those machines where it is available;putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:python3.8to the shell.1 Since the choice of the directory where the interpreter lives is an installation option, other places are possible;check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternativelocation.)On Windows machines where you have installed Python from the Microsoft Store, the python3.8 command will beavailable. If you have the py.exe launcher installed, you can use the py command. See setting-envvars for other ways tolaunch Python.
Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes theinterpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command:quit().
The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems thatsupport the GNU Readline library. Perhaps the quickest check to see whether command line editing is supported is typingControl-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix InteractiveInput Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed,command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it readsand executes commands interactively; when called with a file name argument or with a file as standard input, it reads andexecutes a script from that file.
A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) incommand, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that arespecial to the shell, it is usually advised to quote command in its entirety with single quotes.
Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ...,which executes the source file for module as if you had spelled out its full name on the command line.
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. Thiscan be done by passing -i before the script.
installed Python 2.x executable.

Pretty good!

Cela dit, il est naturel de pouvoir diviser proprement un si beau PDF. Vous pouvez également l'utiliser pour des PDF plus complexes qui basculent entre 1 et 2 colonnes, alors essayez-le.

Résumé

Ce n'est en aucun cas parfait pour chaque PDF, mais c'est un bon. Le PDF japonais est également pris en charge, mais le PDF japonais contient beaucoup de texte dans l'OCR, vous pouvez donc effacer l'espace avec .replace (" "," ") Je pense que ce sera propre (bien que cette méthode ne puisse pas être utilisée si le texte anglais est inclus). Si vous souhaitez traduire un PDF comme mentionné ci-dessus, il existe de nombreuses utilisations, veuillez donc l'utiliser.

Recommended Posts

J'ai créé une fonction qui divise assez bien une copie maladroite d'un texte PDF.
[Discode Bot] J'ai essayé de créer un Bot qui me dit la valeur de race de Pokemon
#Une fonction qui renvoie le code de caractère d'une chaîne de caractères
J'ai fait une fonction pour vérifier le modèle de DCGAN
J'ai essayé un peu le comportement de la fonction zip
J'ai écrit un script qui divise l'image en deux