You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将文本文件中的数据读取并导入字典?

Read Text File Data into a Python Dictionary

Here's a safe and reliable implementation to parse your text file content into a Python dictionary. The key challenge here is handling the unquoted stock ticker keys (like ABB, ABEV) and safely converting the embedded dictionary strings into actual Python objects.

Step-by-Step Code Implementation

import ast
import re

# Open the file and read its content
with open('list_all.csv', mode='r') as inf:
    # Read all content and strip leading/trailing whitespace
    file_content = inf.read().strip()

# Define a regex pattern to extract each ticker and its associated data
# Pattern breakdown:
# - ([A-Z]+): Capture one or more uppercase letters as the ticker key
# - \s*:\s*: Match colon with optional whitespace on either side
# - ({[^}]+}): Capture the entire dictionary string inside curly braces
pattern = r'([A-Z]+)\s*:\s*({[^}]+})'
matches = re.findall(pattern, file_content)

# Build the final dictionary
stock_data = {}
for ticker, dict_string in matches:
    # Safely convert the string dictionary to a Python dict using ast.literal_eval
    stock_data[ticker] = ast.literal_eval(dict_string)

# Example usage: Print the entire dataset
print("Full Stock Data:\n", stock_data)

# Access specific values
print("\nABB's Sector:", stock_data['ABB']['Sector'])
print("ABEV's List Date:", stock_data['ABEV']['List_Date'])

Key Explanations

  • Regex Pattern: The regex efficiently extracts each ticker-key and its corresponding dictionary string, avoiding issues with commas inside the inner dictionaries that would break a simple split operation.
  • ast.literal_eval: This is a safe alternative to eval()—it only evaluates Python literals (dictionaries, lists, strings, numbers) and won't execute arbitrary code, making it secure for parsing external data.
  • Dictionary Construction: We iterate over the regex matches, converting each embedded dictionary string to a real Python dict and adding it to our main stock_data dictionary with the ticker as the key.

Handling Edge Cases

If your file has multiple lines or extra whitespace, the code will still work because read().strip() removes leading/trailing whitespace, and the regex ignores whitespace around the colon separator. For files with very large datasets, this approach remains efficient since it processes the content in a single pass.

内容的提问来源于stack exchange,提问作者blonc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:31:00