利用正则表达式提取一段文字中的数字内容

本文介绍了如何使用Python的re和csv库编写一个函数,从给定文本中提取数字(包括整数和小数),并将这些数字写入CSV文件。示例代码展示了整个过程。
摘要由CSDN通过智能技术生成
import re
import csv

# 从文本中提取数字的函数(包括整数和小数)
def extract_numbers_from_text(text):
    numbers = re.findall(r'\d+\.\d+|\d+', text)
    return numbers

# 将提取的数字写入 CSV 文件
def write_numbers_to_csv(numbers, output_file):
    with open(output_file, mode='w+', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(["Numbers"])
        for number in numbers:
            writer.writerow([number])

# 示例文本
text = ' '
# 提取文本中的数字
numbers = extract_numbers_from_text(text)

# 将提取的数字写入 CSV 文件
output_file = 'extracted_numbers.csv'
write_numbers_to_csv(numbers, output_file)

print(f"提取的数字已写入 {output_file} 文件中。")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值