首页 > 解决方案 > 我的 python 代码中不断出现“invalid \x escape”错误。我究竟做错了什么?

问题描述

我一直在尝试让这段 python 代码在我的计算机上打开一个目录并读取它的内容,这样我就可以为分配生成一个输出,但我不断收到“无效的 \x 转义”。我的有什么问题吗语法还是我的正斜杠和反斜杠都混淆了。

import sys,os,re
import time

定义用作计数器的全局变量

tokens = 0
documents = 0
terms = 0
termindex = 0
docindex = 0 

初始化列表变量

#

alltokens = []
alldocs = []

#

捕获例程的开始时间,以便我们确定总运行时间

处理语料库所需的时间

#

t2 = time.localtime() 

设置语料库的目录名称

#

dirname = "C:\Users\xhenr\Documents\cs3308\cacm"

对于目录中的每个文档,将文档读入字符串

#

all = [f for f in os.listdir(dirname)]
for f in all:
    documents+=1
    with open('C:\Users\xhenr\Documents\cs3308\cacm/f', 'r') as myfile:
        alldocs.append(f)
        data=myfile.read().replace('\n', '')  
        for token in data.split():
            alltokens.append(token)
        tokens+=1

打开为文档字典写入文件

#

documentfile = open('C:/Users/xhenr/Documents/cs3308/cacm/documents.dat', 'w')
alldocs.sort()
for f in alldocs:
  docindex += 1
  documentfile.write(f+','+str(docindex)+os.linesep)
documentfile.close()

#

对列表中的标记进行排序

alltokens.sort()

#

定义唯一术语的列表

g=[]

#

识别语料库中的唯一术语

for i in alltokens:    
    if i not in g:
       g.append(i)
       terms+=1

terms = len(g

)

将索引输出到磁盘文件。作为此过程的一部分,我们为每个唯一术语分配一个“索引”编号。

indexfile = open('C:/Users/xhenr/Documents/cs3308/cacm/index.dat', 'w')
for i in g:
  termindex += 1
  indexfile.write(i+','+str(termindex)+os.linesep)
indexfile.close()

在语料库上打印指标

#

print 'Processing Start Time: %.2d:%.2d' % (t2.tm_hour, t2.tm_min)
print "Documents %i" % documents
print "Tokens %i" % tokens
print "Terms %i" % terms

t2 = time.localtime()   
print 'Processing End Time: %.2d:%.2d' % (t2.tm_hour, t2.tm_min)

标签: python

解决方案


这里:

dirname = "C:\Users\xhenr\Documents\cs3308\cacm"

Python 将反斜杠解释为试图转义以下字符,而实际上它是系统路径。您可以通过转义反斜杠来解决此问题,但有一个更简单的方法:

dirname = r"C:\Users\xhenr\Documents\cs3308\cacm"

通过r在前面放一个,你告诉 Python 按原样处理字符串,不带任何转义字符。(r原始的代表。)这也意味着您也必须更改此行:

with open('C:\Users\xhenr\Documents\cs3308\cacm/f', 'r') as myfile:

变成:

with open(r'C:\Users\xhenr\Documents\cs3308\cacm\f', 'r') as myfile:

(还更改了正斜杠和反斜杠的不一致使用。


推荐阅读