编写程序,在文件夹中生成饭店营业额模拟数据文件 data.csv。并使用datetime模块获得用户用餐时长;使用re模块获得字符串中的名字、电话。
时间: 2024-10-19 09:17:16 浏览: 22
用户用电量数据data.rar
4星 · 用户满意度95%
在Python中,你可以通过以下几个步骤来创建一个名为"data.csv"的模拟饭店营业额文件,并利用`datetime`模块获取用餐时长以及使用`re`模块提取名字和电话:
1. 首先,导入必要的库:
```python
import csv
from datetime import datetime
import random
import re
```
2. 定义模拟数据的结构,比如每行包含日期、时间、顾客名称、电话和消费额:
```python
def generate_data():
# 一些示例数据
customers = [
("张三", "13812345678", "午餐", random.randint(50, 200)),
("李四", "13987654321", "晚餐", random.randint(100, 300)),
# 更多随机数据...
]
with open("data.csv", "w", newline="", encoding="utf-8") as csvfile:
fieldnames = ["Date", "Time", "Customer Name", "Phone", "Amount"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader() # 写入表头
for customer in customers:
date_time = datetime.now().strftime("%Y-%m-%d %H:%M")
row = {
"Date": date_time,
"Time": date_time,
"Customer Name": customer[0],
"Phone": customer[1],
"Amount": str(customer[2]),
}
writer.writerow(row)
```
3. 对于提取名字和电话的正则表达式,假设电话号码是11位数字,名字由汉字和英文字符组成:
```python
def extract_info(text):
name_pattern = r"[\u4e00-\u9fa5a-zA-Z]+"
phone_pattern = r"\b\d{11}\b"
match_name = re.search(name_pattern, text)
match_phone = re.search(phone_pattern, text)
if match_name:
name = match_name.group()
else:
name = "Unknown"
if match_phone:
phone = match_phone.group()
else:
phone = "Unknown"
return name, phone
# 使用示例
text = "欢迎张三先生致电13812345678订餐"
name, phone = extract_info(text)
print(f"Name: {name}, Phone: {phone}")
```
4. 将生成数据和提取信息的部分结合起来,可以循环地读取文件,处理每一行的数据:
```python
if __name__ == "__main__":
generate_data()
# 打开已有的data.csv文件(如果存在),处理每一行数据
with open("data.csv", "r", newline="", encoding="utf-8") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
text = f"{row['Customer Name']} 联系电话: {row['Phone']}"
name, phone = extract_info(text)
print(f"处理记录: {name} ({phone})")
```
阅读全文