简体   繁体   English

扫描字符串文字时停产

[英]EOL while scanning string literal

this is my code and get a following error message: line 8 sepFile=readFile.read().split('\\') SyntaxError: EOL while scanning string literal could you help me? 这是我的代码,并得到以下错误消息:第8行sepFile = readFile.read()。split('\\')SyntaxError:扫描字符串文字时停产可以帮我吗? Thanks. 谢谢。

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()

\\ is a special character in Python string literals: it starts an escape sequence . \\是Python字符串文字中的特殊字符:它开始一个转义序列

To fix the problem, you need to double the backslash: 要解决此问题,您需要将反斜杠加倍:

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

Doing so tells Python that you are using a literal backslash rather than an escape sequence. 这样做会告诉Python您正在使用文字反斜杠,而不是转义序列。


Also, for , like all keywords in Python, needs to be lowercase: 同样, for ,就像Python中的所有关键字一样,需要小写:

for plotPair in sepFile:

You cannot split by '\\' , it is used for special escape sequences such as '\\n' and '\\t' . 您不能用'\\'分割,它用于特殊的转义序列,例如'\\n''\\t' Try a double backslash: '\\\\' . 尝试双反斜杠: '\\\\' Here is your revised code: 这是您的修改后的代码:

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()

Look here for more information on backslashes 在此处查看有关反斜杠的更多信息

StackOverflow's syntax highlighting actually gives a good clue as to why this is happening! 实际上,StackOverflow的语法高亮显示了为什么会发生这种情况的好线索!

The problem is with this line: 问题在于此行:

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

...or more specifically, this: ...或更具体地说,这是:

'\'

That backslash is escaping the last quote, so Python doesn't know that the string has ended. 该反斜杠转义了最后一个引号,因此Python不知道字符串已经结束。 It'll keep going, but the string never terminates, so it throws an exception. 它会继续运行,但是字符串永远不会终止,因此会引发异常。

To fix it, escape the backslash: 要解决此问题,请转义反斜杠:

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

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

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