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

请求协助:读取test.txt文件并转换为值仅为1111的hash

嘿,我来帮你搞定这个需求!首先得明确test.txt里的内容格式是什么样的?不过没关系,我先给你几种常见场景下的实现方案,你可以根据自己的文件结构调整~

基于Python的实现方案

(如果你用的是其他语言,比如Ruby/JavaScript,告诉我我再给你对应的代码哦)

情况1:test.txt每行存储一个独立的key

比如你的test.txt内容是这样的:

username
user_id
phone
address

对应的代码实现:

# 初始化空字典(也就是你说的hash结构)
result_hash = {}

# 使用with语句打开文件,会自动处理文件关闭,更安全
with open('test.txt', 'r', encoding='utf-8') as file:
    # 逐行读取文件内容
    for line in file:
        # 去除每行首尾的空白字符(比如换行符、空格)
        key = line.strip()
        # 跳过空行,避免无效key
        if key:
            # 给每个key赋值固定的value:1111
            result_hash[key] = 1111

# 打印结果验证
print(result_hash)

运行后你会得到:

{'username': 1111, 'user_id': 1111, 'phone': 1111, 'address': 1111}

情况2:test.txt里是已有的key-value格式(比如用=、空格分隔)

比如你的test.txt内容是这样的:

username=zhangsan
user_id=1001
phone=138xxxx1234

我们需要保留原key,把所有value替换成1111,代码如下:

result_hash = {}

with open('test.txt', 'r', encoding='utf-8') as file:
    for line in file:
        cleaned_line = line.strip()
        if cleaned_line:
            # 按分隔符拆分,这里用=作为分隔,split只执行1次,避免key里包含=的情况
            key, _ = cleaned_line.split('=', 1)
            # 给处理后的key赋值1111
            result_hash[key.strip()] = 1111

print(result_hash)

运行后结果:

{'username': 1111, 'user_id': 1111, 'phone': 1111}

补充说明

如果你的test.txt是其他特殊格式(比如JSON、CSV、XML),或者你用的是其他编程语言,欢迎把具体格式或语言告诉我,我再给你针对性的解决方案!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:26:14