Python编辑文本的特定单词

2024-10-01 00:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序是一个基本的Tkinter游戏与记分牌类型系统。此系统将用户名和每个用户的尝试次数存储在文本文件中。你知道吗

例如,当这是用户的第一次时,它会将他们的名字作为[joe\u bloggs,1]附加到文本文件的末尾,其中joe\u bloggs是用户名,1是尝试次数。作为用户的第一次,它是1。你知道吗

我试图寻找一种方法来'更新'或改变数字'1'的增量1每一次。此文本文件以该格式存储所有用户,即[Joe,1][example1,1][example2,2]。你知道吗

以下是我目前拥有的代码:

write = ("[", username, attempts ,"]")

if (username not in filecontents): #Searches the file contents for the username    
    with open("test.txt", "a") as Attempts:    
        Attempts.write(write)
        print("written to file")  

else:
    print("already exists")
    #Here is where I want to have the mechanism to update the number. 

提前谢谢。你知道吗


Tags: theto用户程序系统username次数用户名
2条回答

一个简单的解决方案是使用标准库的^{}模块:

import shelve

scores = shelve.open('scores')
scores['joe_bloggs'] = 1
print(scores['joe_bloggs'])
scores['joe_bloggs'] += 1
print(scores['joe_bloggs'])
scores.close()

输出:

1
2

下次会议:

scores = shelve.open('scores')
print(scores['joe_bloggs'])

输出:

2

A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.

您可以将整个内容转换为字典:

>>> dict(scores)
{'joe_bloggs': 2}

适应您的用例:

username = 'joe_bloggs'

with shelve.open('scores') as scores:  
    if username in scores: 
        scores[username] += 1 
        print("already exists")
    else:
        print("written to file")  
        scores[username] = 1 

如果不想总是检查用户是否已经存在,可以使用defaultdict。首先,创建文件:

from collections import defaultdict
import shelve

with shelve.open('scores', writeback=True) as scores:
    scores['scores'] = defaultdict(int)

稍后,您只需编写scores['scores'][user] += 1

username = 'joe_bloggs'

with shelve.open('scores', writeback=True) as scores:  
    scores['scores'][user] += 1

具有多个用户和增量的示例:

with shelve.open('scores', writeback=True) as scores:
    for user in ['joe_bloggs', 'user2']:
        for score in range(1, 4):
            scores['scores'][user] += 1
            print(user, scores['scores'][user])

输出:

joe_bloggs 1
joe_bloggs 2
joe_bloggs 3
user2 1
user2 2
user2 3

您可以使用标准的ConfigParser模块来持久化简单的应用程序状态。你知道吗

相关问题 更多 >