我最近不得不在我的网站上紧急复制我的数据库。
我使用我在Python中使用管理代码创建的一些函数来删除它。 数据库格式如下:
Name:
Phone Number:
Has played the game:
所有内容都复制在.txt
文件中,但有时,我在文件中发现了一些错误,如:
Name: Name: Name: Bob
如何使用shell命令或Python清除此混乱,但保持相同的顺序(我希望它仍然是姓名,电话号码等)?
答案 0 :(得分:1)
假设您在db.txt
Phone Number:
Phone Number: Phone Number: Phone Number: 0118521358 Name: Name: Name: Name: Bob
Has played the game:
Name: Name: Name: Name: Bob
您可以尝试这样的小脚本
import re
#create a new file called new_file
new_file=open("new_file",'w')
#open the database file with the discrepancies
file_with_error=open('db.txt','r')
#make a list of all your columns in the db
db_header=['Name:','Phone Number:']
#iterate through each line in your database file and find matches to replace
for line in file_with_error:
for col_name in db_header:
line=re.sub("(%s[ ]*)+" %(col_name,),col_name,line)
new_file.write(line) #write your new line your file
new_file.close()
exit(0)
答案 1 :(得分:0)
您可以使用正则表达式来运行字符串匹配,并在文本文件中替换修复此问题。 你可以用python或简单地在像notepad ++这样的编辑器中完成这个。 搜索表达式:
Name:.+(Name: (?!Name:).+)
并将其替换为
$1
在您的文本文件中,此表达式将查找以
开头的所有行Name:
并将其替换为:
Name: Bob
答案 2 :(得分:0)
我假设您知道如何在python中逐行读取文本文件。假设您将每行读入一个名为s
的字符串>>> s = "Name: Name: Name: Bob"
>>> s2 = "Name: Bob"
>>>
>>> s_split = s.split(":")
>>> s_split
['Name', ' Name', ' Name', ' Bob']
>>> result = ": ".join(s_split[-2:])
>>> result
' Name: Bob'
>>> result = ": ".join(s_split[-2:]).strip()
>>> result
'Name: Bob'
第一次拆分会将字符串拆分为字符串列表,其中:是分隔符。连接将获取列表中的最后两个字符串,并将它们与:连接在一起。如果线是正常的,它就可以工作。它也适用于任何数量的错误标签