简体   繁体   English

我的代码为什么要换行

[英]Why does my code make a new line

I'm tasked with taking some baseball team statistics from one txt file, finding the percent of games won, and outputting that to a separate file. 我的任务是从一个txt文件中获取一些棒球队的统计数据,找到获胜百分比,然后将其输出到另一个文件中。

My code is as follows 我的代码如下

infile = open("ALE.txt", "r")
outfile = open("ALE_sorted.txt", "w")

for line in infile:
    data = line.split(',')
    wins = eval(data[2])
    percentage = 162 / wins

    outfile.write(str(data[0]) + ", " + data[1] + ", " + data[2] + ", " + 
str(round(percentage, 3)) + "\n")

infile.close()
outfile.close()

The initial txt file looks like this in the format (teams, wins, losses): 初始txt文件的格式如下(团队,获胜和损失):

Baltimore,93,69 巴尔的摩93,69
Boston,69,93 波士顿69,93
New York,95,67 纽约95,67
Tampa Bay,90,72 坦帕湾90,72
Toronto,73,89 多伦多73,89

And while my code correctly calculates the percentage of games won, it creates a line and I can't figure out why, looking exactly like this: 虽然我的代码正确地计算了获胜的百分比,但它会创建一条线,但我不知道为什么,看起来像这样:

Baltimore, 93, 69 巴尔的摩,93,69
, 2.348 ,2.348
Boston, 69, 93 波士顿,69,93
, 1.742 ,1.742
New York, 95, 67 纽约,95,67
, 2.418 ,2.418
Tampa Bay, 90, 72 坦帕湾,90,72
, 2.25 ,2.25
Toronto, 73, 89, 1.82 多伦多,73,89,1.82

It should only be 5 lines, not creating a new line right before the third comma every time. 它只能是5行,而不是每次都在第三个逗号之前创建新行。 I've tried removing the "\\n" but to no avail. 我尝试删除“ \\ n”,但无济于事。 Any tips? 有小费吗?

Try changing: 尝试更改:

data = line.split(',')

to: 至:

data = line.strip().split(',')

"line" is defined as "string of characters ending in line terminator". “行”定义为“以行终止符结尾的字符串”。 Thus, after you read the first line, line contains "Baltimore,93,69\\n" . 因此,在阅读第一行之后,该line包含"Baltimore,93,69\\n" After split, data is ["Baltimore", "93", "69\\n"] . 拆分后, data["Baltimore", "93", "69\\n"] When you print out data[2] , there's a newline - because you never removed it. 打印data[2] ,会有一个换行符-因为您从未删除过它。

Use data = line.rstrip('\\n').split(',') to remove it. 使用data = line.rstrip('\\n').split(',')删除它。 rstrip removes specified characters from the end of the string. rstrip从字符串末尾删除指定的字符。 .rstrip() would also work, but it removes any whitespace (such as trailing spaces). .rstrip()也可以,但是它将删除所有空白(例如尾随空格)。

Your data[2] includes a newline. 您的data[2]包含换行符。 Just strip it away. 只需将其剥离即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM