簡體   English   中英

如何修復python代碼中的語法錯誤?

[英]How can I fix syntax-error in python code?

我正在從網站上關注本教程: https : //towardsdatascience.com/creating-the-twitter-sentiment-analysis-program-in-python-with-naive-bayes-classification-672e5589a7ed到目前為止一切都很好,但我嘗試運行此代碼時不斷收到錯誤消息。

def buildTrainingSet(corpusFile, tweetDataFile):
import csv
import time

corpus = []

with open(corpusFile,'rb') as csvfile:
    lineReader = csv.reader(csvfile,delimiter=',', quotechar="\"")
    for row in lineReader:
        corpus.append({"tweet_id":row[2], "label":row[1], "topic":row[0]})

rate_limit = 180
sleep_time = 900/180

trainingDataSet = []

for tweet in corpus:
    try:
        status = twitter_api.GetStatus(tweet["tweet_id"])
        print("Tweet fetched" + status.text)
        tweet["text"] = status.text
        trainingDataSet.append(tweet)
        time.sleep(sleep_time) 
    except: 
        continue
# now we write them to the empty CSV file
with open(tweetDataFile,'wb') as csvfile:
    linewriter = csv.writer(csvfile,delimiter=',',quotechar="\"")
    for tweet in trainingDataSet:
        try:
            linewriter.writerow([tweet["tweet_id"], tweet["text"], tweet["label"], tweet["topic"]])
        except Exception as e:
            print(e)
return trainingDataSet
 #================
corpusFile = "C:\Users\Vilma\Documents\CIS450\group prjt/corpus.csv"
tweetDataFile = "C:\Users\Vilma\Documents\CIS450\group prjt/tweetDataFile.csv"

trainingData = buildTrainingSet (corpusFile, tweetDataFile)

我不斷收到此錯誤:

 File "<ipython-input-33-54fea359e8f9>", line 1
    corpusFile = "C:\Users\Vilma\Documents\CIS450\group prjt/corpus.csv"
                ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

我什至嘗試將 r' 放在 C:\\Users\\Vilma\\Documents\\CIS450\\group prjt/corpus.csv 前面,但我仍然收到錯誤。

更新:修正錯誤,我把代碼作為

corpusFile = r'C:\Users\Vilma\Documents\CIS450\group prjt\corpus.csv'
tweetDataFile = r'C:\Users\Vilma\Documents\CIS450\group prjt\tweetDataFile.csv'

但是,彈出一個新錯誤:

File "<ipython-input-41-f44768dabc6e>", line 7, in buildTrainingSet
    with open(corpusFile,'rb') as csvfile:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Vilma\\Documents\\CIS450\\group prjt\\corpus.csv'

嘗試更正您的文件路徑。

corpusFile = "C:\Users\Vilma\Documents\CIS450\group prjt/corpus.csv"

    Should be:

    corpusFile = "C:\Users\Vilma\Documents\CIS450\group prjt\corpus.csv"

希望這可以幫助!

您可以使用:

corpusFile = r"C:\\Users\\Vilma\\Documents\\CIS450\\group prjt\\corpus.csv"

如果您沒有找到該文件,請確保該文件存在於文件夾中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM