So extrahieren Sie die Daten (Zahlen) aus einer Datei mit regulärem Ausdruck in Python | von Haseeba | Juni 2023

0
27


Foto von Ryoji Iwata An Unsplash

In diesem Artikel extrahieren wir die Daten aus einer Datei mit regulärem Ausdruck.

Was ist ein regulärer Ausdruck?

Ein regulärer Ausdruck (oder Regex) bietet eine präzise und versatile Möglichkeit, Textzeichenfolgen wie bestimmte Zeichen, Wörter oder Zeichenmuster abzugleichen.

Python Common Expression Fast Information

^ Matches the start of a line
$ Matches the tip of the road
. Matches any character
s Matches whitespace
S Matches any non-whitespace character
* Repeats a personality zero or extra instances
*? Repeats a personality zero or extra instances
(non-greedy)
+ Repeats a personality a number of instances
+? Repeats a personality a number of instances
(non-greedy)
[aeiou] Matches a single character within the listed set
[^XYZ] Matches a single character not within the listed set
[a-z0-9] The set of characters can embrace a variety
( Signifies the place string extraction is to start out
) Signifies the place string extraction is to finish

wir haben eine Datei regex_sum_1750385.txt. Sie können diese Datei auf dieser Web site überprüfen

https://py4e-data.dr-chuck.net/regex_sum_42.txt

import re
textual content=open("regex_sum_1750385.txt", 'r')
textual content=textual content.learn()
x=re.findall('[0-9]+',textual content)
x = [int(i) for i in x]
print('listing of quantity from the file:', x)
sum_of_numbers=sum(x)
print('sum of numbers:', sum_of_numbers)

Zuerst müssen wir re(regulären Ausdruck) importieren, dann öffnen wir die Datei und lesen sie.

findall(): findet *alle* Übereinstimmungen und gibt sie als Liste von Zeichenfolgen zurück, wobei jede Zeichenfolge eine Übereinstimmung darstellt, wobei wir die Übereinstimmungen der Ziffern zwischen null und 9 finden.

Anschließend konvertieren wir diese Ziffern mithilfe des Listenverständnisses aus Zeichenfolgen in Ganzzahlen. Summieren Sie diese Zahlen.

Ausgang:

listing of quantity from the file: [8162, 2094, 7718, 5172, 4660, 3780, 9393, 4594, 4939, 6986, 5411, 8200, 3124, 2875, 2664, 7612, 3672, 6816, 6757, 8085, 8544, 7616, 5283, 9566, 6819, 8761, 4703, 324, 4580, 1963, 1311, 7636, 9494, 9437, 4499, 7144, 234, 7797, 5161, 1207, 2485, 482, 3986, 5800, 784, 4325, 5092, 6534, 3048, 2800, 7262, 2680, 4, 7268, 5991, 474, 4916, 7918, 5357, 3083, 3913, 7867, 4743, 905, 8419, 2870, 6879, 6737, 1643, 9173, 3602, 4, 3, 42]
sum of numbers: 361882



Source link

HINTERLASSEN SIE EINE ANTWORT

Please enter your comment!
Please enter your name here