字符串文字扫描时出现 EOL 错误

3
这是我的代码,但出现了以下错误信息: 第8行sepFile=readFile.read().split('\') SyntaxError: EOL while scanning string literal 你能帮我解决一下吗? 谢谢。
import matplotlib.pyplot as plt
import numpy as np
x=[]
y=[]

readFile = open (("/Users/Sun/Desktop/text58.txt"), 'r')

sepFile=readFile.read().split('\')
readFile.close()

For plotPair in sepFile:
    xANDy=plotPair.split(',')
    x.append(int(xAndy[2]))
    y.append(int(xAndy[1]))
print x
print y

plt.plot(x,y)

plt.title('tweet')
plt.xlabel('')
plt.ylabel('')
plt.show()

我有4个撇号符号表示我的注释部分。当我将其改为3时,这个错误消失了。 - pnv
3个回答

6

\ 是Python字符串字面值中的特殊字符:它开始一个转义序列

为了解决问题,您需要将反斜杠加倍:

sepFile=readFile.read().split('\\')

这样做告诉Python你正在使用一个字面上的反斜杠而不是转义序列。


此外,像Python中的所有关键字一样,for也需要小写。
for plotPair in sepFile:

2

您不能使用 '\' 进行分割,因为它用于特殊的转义序列,例如 '\n''\t'。请尝试使用双反斜杠:'\\'。以下是修改后的代码:

import matplotlib.pyplot as plt
import numpy as np
x=[]
y=[]

readFile = open (("/Users/Sun/Desktop/text58.txt"), 'r')

sepFile=readFile.read().split('\\')
readFile.close()

For plotPair in sepFile:
    xANDy=plotPair.split(',')
    x.append(int(xAndy[2]))
    y.append(int(xAndy[1]))
print x
print y

plt.plot(x,y)

plt.title('tweet')
plt.xlabel('')
plt.ylabel('')
plt.show()

点击此处获取有关反斜杠的更多信息


0
StackOverflow 的语法高亮实际上很好地提示了这是为什么!
问题出在这一行:
sepFile=readFile.read().split('\')

...或者更具体地说,这个:

'\'

那个反斜杠是用来转义最后一个引号的,所以Python不知道字符串何时结束。它会继续执行,但是字符串永远不会终止,因此会抛出异常。

要解决这个问题,需要转义反斜杠:

sepFile=readFile.read().split('\\')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接