RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 767578
Accepted
андрей гривкин
андрей гривкин
Asked:2020-01-07 17:52:40 +0000 UTC2020-01-07 17:52:40 +0000 UTC 2020-01-07 17:52:40 +0000 UTC

从文件中获取字符串并将其转换为 int Python 类型

  • 772

该函数从 users.txt 文件中读取用户的登录名(那里总是只有一个登录名),然后查找相同的 inprogress.txt,如果找到,则需要将登录名后面的行替换为再一个,从 1 到 2,从 2 等。.d。是班级编号。如果是第一次输入登录名,那么只需将其写入progress后跟1。问题是我不明白如何从文件中获取带有数字的这一行,将其转换为int,加1,然后把它写到同一个地方。或许答案是显而易见的,但我对 Python 才熟悉几天,还是不太了解。提前致谢

with open('users.txt', 'r') as f:
line = f.readline()
f.close()
with open('progress.txt', 'r') as k:
while True:
    global uroka_in
    lines = k.readline()
    if line == lines.rstrip():
        uroka_in = int(k.readline().rstrip())
        urokb_in = uroka_in + 1
        uroka_str = str(uroka_in)
        urokb_str = str(urokb_in)
        lines.replace(uroka_str, urokb_str)
        k.close()
        break
    if not lines:
        k.close()
        global urokb_in
        urokb_in = 1
        with open('progress.txt', 'a') as j:
            j.write(line)
            j.write('\n')
            j.write(str(urokb_in))
            j.write('\n')
            j.close()
            break

示例 progress.txt 文件:

username1
1
username2
1
username3
1

编辑:

def user():
with open('users.txt') as k:
    user = k.readline()
    k.close()
def increment_counter(user, 'progress.txt'):
    with open('progress.txt', 'r') as f:
     data = yaml.safe_load(f.read())
    data[user] += 1
    with open('progress.txt', 'w') as f:
    yaml.dump(data, f, indent=2, default_flow_style=False)
python
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. MaxU - stop genocide of UA
    2020-01-08T00:31:29Z2020-01-08T00:31:29Z

    试试这样:

    import yaml   #  требует установленного модуля `yaml`: pip install pyyaml
    
    def get_user(filename=r'/path/to/users.txt'):
        with open(filename) as f:
            return f.readline()
    
    def increment_counter(user, filename):
        with open(filename, 'r') as f:
            data = yaml.safe_load(f.read())
        data[user] += 1
        with open(filename, 'w') as f:
            yaml.dump(data, f, indent=2, default_flow_style=False)
    

    使用示例:

    increment_counter(get_user(r'/path/to/users.txt'), r'/path/to/progress.yml')
    

    progress.yml函数调用之前的示例 YAML 文件 ( ):

    username1: 1
    username2: 1
    username3: 1
    

    "progress.yml"通话后内容increment_counter('username3', r'/path/to/progress.yml'):

    username1: 1
    username2: 1
    username3: 2
    

    纯文本文件的功能(如问题所示)

    def increment_counter(user, filename):
        with open(filename, 'r') as f:
            data = f.read()
        with open(filename, 'w') as f:
            pat = r'(' + user + r'[\r\n]+)(\d+)'
            m = re.search(pat, data)
            if m:
                s = m.group(1)
                s += str(int(m.group(2)) + 1)
                new = re.sub(pat, s, data)
                f.write(new)
            else:
                f.write(data)
    

    使用示例:

    increment_counter('username3', r'/path/to/progress.txt')
    

    PS 我推荐使用 YAML 来存储用户数据

    • 1
  2. Best Answer
    vadim vaduxa
    2020-01-08T03:49:09Z2020-01-08T03:49:09Z
    import json
    
    def progress():
        #p_dict = eval(open('progress.txt').read())
        p_dict = json.load(open('progress.txt'))
        user = next(filter(bool, map(str.strip, open('users.txt'))))
    
        if user in p_dict:
            p_dict[user] += 1
        else:
            p_dict[user] = 1
    
        with open('progress.txt', 'w') as f:
            json.dump(p_dict, f, indent=0, sort_keys=True)
    

    例如'progress.txt'

    {
    "user0": 1,
    "user1": 4,
    "user3": 2
    }
    

    空的“progress.txt”最初应该包含一行:{}

    另一种选择,正如问题作者想要的那样:

    def progress():
        iter_lines = filter(bool, map(str.strip, open('progress.txt')))
        p_dict = {k: int(v) for k, v in zip(iter_lines, iter_lines)}
        user = next(filter(bool, map(str.strip, open('users.txt'))))
    
        if user in p_dict:
            p_dict[user] += 1
        else:
            p_dict[user] = 1
    
        with open('progress.txt', 'w') as f:
            f.write('\n'.join('{}\n{}'.format(k, p_dict[k]) for k in p_dict))
    
        return user, p_dict
    

    例如'progress.txt'

    user0
    1
    user1
    4
    user3
    2
    
    • 1

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5