简体   繁体   中英

how can i separate float numbers from a .docx file and add it to a list?

 from docx import Document
    numbers = []
    doc = Document('word.docx')
    for para in doc.paragraphs:
        new_text = para.text
        for char in new_text:
            if char in '0123456789.':
                numbers.append(char)
        print(new_text)
    
    print(numbers)

*its a persian language docx file

it return this:

بزرگترین جانور از تیرهٔ و بومی آسیا است که طول بدن آن به 2.7 تا 3 متر و وزن آن به 306 می‌رسد. مهم‌ترین مشخصهٔ این جانور، خط‌های عمودی تیره روی خز قرمز-نارنجی آن است که در ناحیهٔ زیرین روشن‌تر است. این جانور دارای بدنی عضلانی و پاهایی بسیار نیرومند است. بدن ببر دارای موهای بلند و برّاق به رنگ ، همراه با خط‌های سیاه عمودی می‌باشد. جثّهٔ ببرهای نر بزرگ‌تر از ببرهای ماده است و همچنین موهای روی گونهٔ ببر نر بلندتر از ببر ماده می‌باشد. دندان‌های ببر بسیار قوی است و در میان جانوران خشکی بلندترین است. طول ببر به 74.5 میلی‌متر و گاهی تا 90 میلی‌متر می‌رسد. در ببرها معمولاً بین 10تا15 سال عمر می‌کنند. بیشترین طول عمر ثبت شده در باغ‌ وحش‌ها 26 سال گزارش شده‌است.

['2', '.', '7', '3', '3', '0', '6', '.', '.', '.', '.', '.', '.', '7', '4', '.', '5', '9', '0', '.', '1', '0', '1', '5', '.', '2', '6', '.']

as you can see it add periods of text to list as well.

Of course it captures all periods, since you allow them in your character list. To recognize numbers, you can't just inspect individual characters, though, but groups of them. You can do that rather simply by using regular expressions :

In [7]: re.findall("\d+(?:\.\d+)?", text)
Out[7]: ['2.7', '3', '306', '74.5', '90', '10', '15', '26']

(That's just an example, in reality you would need to find a pattern matching your use case and should compile it before usage with re.compile .)

Then you just need to convert the results:

In [8]: [float(x) for x in re.findall("\d+(?:\.\d+)?", text)]
Out[8]: [2.7, 3.0, 306.0, 74.5, 90.0, 10.0, 15.0, 26.0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM