I have a text file which stores data like name : score
e.g.:
我有一个文本文件存储数据,如名称:分数例如:
bob : 10
fred : 3
george : 5鲍勃:10弗雷德:3乔治:5
However, I want to make it so it says
但是,我想这样说
10 : bob
3 : fred
5 : george10:鲍勃3:弗雷德5:乔治
What would the code be to flip it like that? Would I need to separate them first by removing the colon as I have managed this through this code?
那些代码会像那样翻转它?我是否需要首先删除冒号,因为我通过此代码管理了这个?
file = open("Class 3.txt", "r")
t4 = (file.read())
test =''.join(t4.split(':')[0:10])
print (test)
How would I finish it and make it say the reverse?
我怎么完成它并让它反过来说?
3 个解决方案
#1
This code handles fractional scores (e.g. 9.5
), and doesn't care whether there are extra spaces around the :
delimiter. It should be much easier to maintain than your current code.
此代码处理小数分数(例如9.5),并不关心:分隔符周围是否有额外的空格。它应该比您当前的代码更容易维护。
Class 3.txt:
bob : 10
fred : 3
george : 5
Code:
class_num = input('Which class (1, 2, or 3)? ')
score_sort = input('Sort by name or score? ').lower().startswith('s')
with open("Class " + class_num + ".txt", "r") as f:
scores = {name.strip():float(score) for
name,score in (line.strip().split(':') for line in f)}
if score_sort:
for name in sorted(scores, key=scores.get, reverse=True):
print(scores.get(name), ':', name)
else:
for name in sorted(scores):
print(name, ':', scores.get(name))
Input:
3
scores
Output:
10.0 : bob
5.0 : george
3.0 : fred
Input:
3
name
Output:
bob : 10.0
fred : 3.0
george : 5.0
#2
First, this is going to be a lot harder to do whole-file-at-once than line-at-a-time.
首先,一次整个文件要比一次一行完成要困难得多。
But, either way, you obviously can't just split(':')
and then ''.join(…)
. All that's going to do is replace colons with nothing. You obviously need ':'.join(…)
to put the colons back in.
但是,无论哪种方式,你显然不能只拆分(':')然后''。join(...)。所有这一切都是用冒险替换冒号。你显然需要':'。join(...)把冒号放回去。
And meanwhile, you have to swap the values around on each side of each colon.
同时,你必须在每个冒号的每一侧交换值。
So, here's a function that takes just one line, and swaps the sides:
所以,这是一个只占一行的函数,并交换边:
def swap_sides(line):
left, right = line.split(':')
return ':'.join((right, left))
But you'll notice there's a few problems here. The left
has a space before the colon; the right
has a space after the colon, and a newline at the end. How are you going to deal with that?
但是你会注意到这里有一些问题。左边有一个结肠前的空间;右边在冒号后面有一个空格,在结尾处有一个换行符。你打算如何应对?
The simplest way is to just strip
out all the whitespace on both sides, then add back in the whitespace you want:
最简单的方法是去掉两边的所有空格,然后在你想要的空白处添加:
def swap_sides(line):
left, right = line.split(':')
return ':'.join((right.strip() + ' ', ' ' + left.strip())) + '\n'
But a smarter idea is to treat the space around the colon as part of the delimiter. (The newline, you'll still need to handle manually.)
但更聪明的想法是将结肠周围的空间视为分隔符的一部分。 (换行符,您仍然需要手动处理。)
def swap_sides(line):
left, right = line.strip().split(' : ')
return ' : '.join((right.strip(), left.strip())) + '\n'
But if you think about it, do you really need to add the newline back on? If you're just going to pass it to print
, the answer is obviously no. So:
但是如果你考虑一下,你真的需要重新添加换行符吗?如果您打算将其传递给打印,答案显然是否定的。所以:
def swap_sides(line):
left, right = line.strip().split(' : ')
return ' : '.join((right.strip(), left.strip()))
Anyway, once you're happy with this function, you just write a loop that calls it once for each line. For example:
无论如何,一旦你对这个函数感到满意,你只需编写一个循环,为每一行调用一次。例如:
with open("Class 3.txt", "r") as file:
for line in file:
swapped_line = swap_sides(line)
print(swapped_line)
#3
Let's learn how to reverse a single line:
让我们学习如何反转一行:
line = `bob : 10`
line.partition(' : ') # ('10', ' : ', 'bob')
''.join(reversed(line.partition(' : ')) # 'bob : 10'
Now, combine with reading lines from a file:
现在,结合文件中的读取行:
for line in open('Class 3.txt').read().splitlines():
print ''.join(reversed(line.partition(' : '))
Update
I am re-writing the code to read the file, line by line:
我正在重写代码来逐行读取文件:
with open('Class 3.txt') as input_file:
for line in input_file:
line = line.strip()
print ''.join(reversed(line.partition(' : ')))
#1
This code handles fractional scores (e.g. 9.5
), and doesn't care whether there are extra spaces around the :
delimiter. It should be much easier to maintain than your current code.
此代码处理小数分数(例如9.5),并不关心:分隔符周围是否有额外的空格。它应该比您当前的代码更容易维护。
Class 3.txt:
bob : 10
fred : 3
george : 5
Code:
class_num = input('Which class (1, 2, or 3)? ')
score_sort = input('Sort by name or score? ').lower().startswith('s')
with open("Class " + class_num + ".txt", "r") as f:
scores = {name.strip():float(score) for
name,score in (line.strip().split(':') for line in f)}
if score_sort:
for name in sorted(scores, key=scores.get, reverse=True):
print(scores.get(name), ':', name)
else:
for name in sorted(scores):
print(name, ':', scores.get(name))
Input:
3
scores
Output:
10.0 : bob
5.0 : george
3.0 : fred
Input:
3
name
Output:
bob : 10.0
fred : 3.0
george : 5.0
#2
First, this is going to be a lot harder to do whole-file-at-once than line-at-a-time.
首先,一次整个文件要比一次一行完成要困难得多。
But, either way, you obviously can't just split(':')
and then ''.join(…)
. All that's going to do is replace colons with nothing. You obviously need ':'.join(…)
to put the colons back in.
但是,无论哪种方式,你显然不能只拆分(':')然后''。join(...)。所有这一切都是用冒险替换冒号。你显然需要':'。join(...)把冒号放回去。
And meanwhile, you have to swap the values around on each side of each colon.
同时,你必须在每个冒号的每一侧交换值。
So, here's a function that takes just one line, and swaps the sides:
所以,这是一个只占一行的函数,并交换边:
def swap_sides(line):
left, right = line.split(':')
return ':'.join((right, left))
But you'll notice there's a few problems here. The left
has a space before the colon; the right
has a space after the colon, and a newline at the end. How are you going to deal with that?
但是你会注意到这里有一些问题。左边有一个结肠前的空间;右边在冒号后面有一个空格,在结尾处有一个换行符。你打算如何应对?
The simplest way is to just strip
out all the whitespace on both sides, then add back in the whitespace you want:
最简单的方法是去掉两边的所有空格,然后在你想要的空白处添加:
def swap_sides(line):
left, right = line.split(':')
return ':'.join((right.strip() + ' ', ' ' + left.strip())) + '\n'
But a smarter idea is to treat the space around the colon as part of the delimiter. (The newline, you'll still need to handle manually.)
但更聪明的想法是将结肠周围的空间视为分隔符的一部分。 (换行符,您仍然需要手动处理。)
def swap_sides(line):
left, right = line.strip().split(' : ')
return ' : '.join((right.strip(), left.strip())) + '\n'
But if you think about it, do you really need to add the newline back on? If you're just going to pass it to print
, the answer is obviously no. So:
但是如果你考虑一下,你真的需要重新添加换行符吗?如果您打算将其传递给打印,答案显然是否定的。所以:
def swap_sides(line):
left, right = line.strip().split(' : ')
return ' : '.join((right.strip(), left.strip()))
Anyway, once you're happy with this function, you just write a loop that calls it once for each line. For example:
无论如何,一旦你对这个函数感到满意,你只需编写一个循环,为每一行调用一次。例如:
with open("Class 3.txt", "r") as file:
for line in file:
swapped_line = swap_sides(line)
print(swapped_line)
#3
Let's learn how to reverse a single line:
让我们学习如何反转一行:
line = `bob : 10`
line.partition(' : ') # ('10', ' : ', 'bob')
''.join(reversed(line.partition(' : ')) # 'bob : 10'
Now, combine with reading lines from a file:
现在,结合文件中的读取行:
for line in open('Class 3.txt').read().splitlines():
print ''.join(reversed(line.partition(' : '))
Update
I am re-writing the code to read the file, line by line:
我正在重写代码来逐行读取文件:
with open('Class 3.txt') as input_file:
for line in input_file:
line = line.strip()
print ''.join(reversed(line.partition(' : ')))