- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我是 Python 的新手,目前正在使用 Python 2。我有一些源文件,每个文件都包含大量数据(大约 1900 万行)。它看起来像下面这样:
apple \t N \t apple
n&apos
garden \t N \t garden
b\ta\md
great \t Adj \t great
nice \t Adj \t (unknown)
etc
我的任务是在每个文件的第 3 列中搜索一些目标词,每次在语料库中找到一个目标词,就必须将这个词前后的 10 个词添加到多维词典中。
编辑:应排除包含“&”、“\”或字符串“(unknown)”的行。
我尝试使用 readlines() 和 enumerate() 来解决这个问题,如下面的代码所示。代码做了它应该做的,但对于源文件中提供的数据量来说,它显然不够高效。
我知道 readlines() 或 read() 不应该用于巨大的数据集,因为它将整个文件加载到内存中。尽管如此,逐行读取文件,我并没有设法使用枚举方法来获取目标词前后的10个词。我也不能使用 mmap,因为我无权在该文件上使用它。
因此,我想具有一定大小限制的 readlines 方法将是最有效的解决方案。但是,为此,我会不会犯一些错误,因为每次到达大小限制的末尾时,目标词之后的 10 个词都不会被捕获,因为代码刚刚中断?
def get_target_to_dict(file):
targets_dict = {}
with open(file) as f:
for line in f:
targets_dict[line.strip()] = {}
return targets_dict
targets_dict = get_target_to_dict('targets_uniq.txt')
# browse directory and process each file
# find the target words to include the 10 words before and after to the dictionary
# exclude lines starting with <,-,; to just have raw text
def get_co_occurence(path_file_dir, targets, results):
lines = []
for file in os.listdir(path_file_dir):
if file.startswith('corpus'):
path_file = os.path.join(path_file_dir, file)
with gzip.open(path_file) as corpusfile:
# PROBLEMATIC CODE HERE
# lines = corpusfile.readlines()
for line in corpusfile:
if re.match('[A-Z]|[a-z]', line):
if '(unknown)' in line:
continue
elif '\\' in line:
continue
elif '&' in line:
continue
lines.append(line)
for i, line in enumerate(lines):
line = line.strip()
if re.match('[A-Z][a-z]', line):
parts = line.split('\t')
lemma = parts[2]
if lemma in targets:
pos = parts[1]
if pos not in targets[lemma]:
targets[lemma][pos] = {}
counts = targets[lemma][pos]
context = []
# look at 10 previous lines
for j in range(max(0, i-10), i):
context.append(lines[j])
# look at the next 10 lines
for j in range(i+1, min(i+11, len(lines))):
context.append(lines[j])
# END OF PROBLEMATIC CODE
for context_line in context:
context_line = context_line.strip()
parts_context = context_line.split('\t')
context_lemma = parts_context[2]
if context_lemma not in counts:
counts[context_lemma] = {}
context_pos = parts_context[1]
if context_pos not in counts[context_lemma]:
counts[context_lemma][context_pos] = 0
counts[context_lemma][context_pos] += 1
csvwriter = csv.writer(results, delimiter='\t')
for k,v in targets.iteritems():
for k2,v2 in v.iteritems():
for k3,v3 in v2.iteritems():
for k4,v4 in v3.iteritems():
csvwriter.writerow([str(k), str(k2), str(k3), str(k4), str(v4)])
#print(str(k) + "\t" + str(k2) + "\t" + str(k3) + "\t" + str(k4) + "\t" + str(v4))
results = open('results_corpus.csv', 'wb')
word_occurrence = get_co_occurence(path_file_dir, targets_dict, results)
出于完整性原因,我复制了整个代码部分,因为它是一个函数的所有部分,该函数根据提取的所有信息创建多维字典,然后将其写入 csv 文件。
如果有任何提示或建议可以提高此代码的效率,我将不胜感激。
编辑 我更正了代码,以便它准确地考虑目标词前后的 10 个词
最佳答案
我的想法是在 10 行之前创建一个缓冲区来存储,在 10 行之后创建一个缓冲区来存储,作为正在读取的文件,它将被插入缓冲区之前,如果大小超过 10,缓冲区将被弹出
对于后缓冲区,我从文件迭代器 1st 克隆了另一个迭代器。然后在循环中并行运行两个迭代器,克隆迭代器提前运行 10 次迭代以获得后 10 行。
这避免了使用 readlines() 并将整个文件加载到内存中。希望在实际案例中对你有用
已编辑:如果第 3 列不包含“&”、“\”、“(未知)”中的任何一个,则仅填充前后缓冲区。还将 split('\t') 更改为 split() 以便它处理所有空格或选项卡
import itertools
def get_co_occurence(path_file_dir, targets, results):
excluded_words = ['&', '\\', '(unknown)'] # modify excluded words here
for file in os.listdir(path_file_dir):
if file.startswith('testset'):
path_file = os.path.join(path_file_dir, file)
with open(path_file) as corpusfile:
# CHANGED CODE HERE
before_buf = [] # buffer to store before 10 lines
after_buf = [] # buffer to store after 10 lines
corpusfile, corpusfile_clone = itertools.tee(corpusfile) # clone file iterator to access next 10 lines
for line in corpusfile:
line = line.strip()
if re.match('[A-Z]|[a-z]', line):
parts = line.split()
lemma = parts[2]
# before buffer handling, fill buffer excluded line contains any of excluded words
if not any(w in line for w in excluded_words):
before_buf.append(line) # append to before buffer
if len(before_buf)>11:
before_buf.pop(0) # keep the buffer at size 10
# next buffer handling
while len(after_buf)<=10:
try:
after = next(corpusfile_clone) # advance 1 iterator
after_lemma = ''
after_tmp = after.split()
if re.match('[A-Z]|[a-z]', after) and len(after_tmp)>2:
after_lemma = after_tmp[2]
except StopIteration:
break # copy iterator will exhaust 1st coz its 10 iteration ahead
if after_lemma and not any(w in after for w in excluded_words):
after_buf.append(after) # append to buffer
# print 'after',z,after, ' - ',after_lemma
if (after_buf and line in after_buf[0]):
after_buf.pop(0) # pop off one ready for next
if lemma in targets:
pos = parts[1]
if pos not in targets[lemma]:
targets[lemma][pos] = {}
counts = targets[lemma][pos]
# context = []
# look at 10 previous lines
context= before_buf[:-1] # minus out current line
# look at the next 10 lines
context.extend(after_buf)
# END OF CHANGED CODE
# CONTINUE YOUR STUFF HERE WITH CONTEXT
关于python - 通过 readlines(size) 提高大文件搜索的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40545045/
这个问题在这里已经有了答案: What could be the reason that `require` doesn't work in some places? (3 个回答) 6 个月前关闭。
我正在使用读取行从维基百科获取一些文本。但读取行仅返回列表,而不是我想要的文本。有什么方法可以使用替代方案或解决我的问题吗? public class mediawiki { public s
我正在编写一小段代码,其中涉及使用子进程运行一个脚本来监听一些实时数据 这是我的代码: def subscriber(): try: sub = subprocess.Pope
我已包括: #include "stdio.h" #include #include 我的编译器包含标志 -lreadline 但我仍然收到错误消息: fatal error: 'readl
使用 Term::Readline::readline 停止无限循环的正确方法是什么? ? 这样我一个都看不懂 0 #!/usr/bin/env perl use warnings; use stri
标题比我的实际目标更具体: 我有一个使用 GNU Readline 的命令行程序,主要用于命令历史记录(即使用向上箭头检索以前的命令)和其他一些细节。现在,程序的输出似乎散布在用户的输入中,有时是可以
在 ipython 中,如果我按“esc”,然后按“enter”(可能还有其他字符?),读行会中断。我无法再使用“向上”键搜索命令历史记录,并且某些命令(例如 control-K)失败。 有没有办法在
我在使用 readlines() 和 readline() 返回值时遇到问题,但在使用 read() 时却没有。任何人都知道这是怎么发生的?欣赏一下 with open('seatninger.txt
标题比我的实际目标更具体: 我有一个使用 GNU Readline 的命令行程序,主要用于命令历史记录(即使用向上箭头检索以前的命令)和其他一些细节。现在,程序的输出似乎散布在用户的输入中,有时是可以
我正在编写一个聊天客户端,它必须在接收用户输入的同时输出接收到的消息。 到目前为止,我已经 fork 成两个独立的进程,其中一个继续监听套接字连接并用 printf 写出接收到的字符串。另一个使用 r
我在 NetworkStream 上使用 StreamReader,我只想读取一行或多行,而另一个数据是 byte array(如文件数据)我不想在 StreamReader 中读取该文件数据,例如我
我遇到了这两个 API,用于在 C# 的简单控制台应用程序中读取用户的输入: System.Console.ReadLine() System.Console.In.ReadLine() 这是一个我试
yum 我的系统显示已安装 readline rlwrap-0.41]$ sudo yum install readline Loaded plugins: fastestmirror, presto
我尝试做 this tutorial在 Rust 中,到目前为止,我在将 C 库连接到 Rust 时遇到了很多问题。 C 等效代码: #include #include #include #in
我正在寻找 web Python的标题中提到的命令及其区别;但是,我并不满足于对这些命令有完整的基本理解。 假设我的文件只有以下内容。 This is the first time I am posi
你如何在 F# 中使用 Console.Readline?与 Console.Writeline 不同,当我调用它时,它并没有受到尊重。 最佳答案 如果你使用 let s = Console.Read
在一次面试中,面试官问我为什么 readline() 比 Python 中的 readlines() 慢很多? 我回答的是readlines()需要多次读取,需要更多的开销。 不知道我的回答对不对。
要在 OSX Lion 上完全运行 ipython 需要什么?我试图让 ipython 与 readline 一起工作,但没有成功。 我的做法: (在虚拟环境中) pip install ipytho
在 Nodejs 文档中,我看到: import EventEmitter from 'events'; import { readFile } from 'fs'; import fs, { rea
我写了一个简单的应用程序: #include #include #include #include int main() { char *user_input; while(u
我是一名优秀的程序员,十分优秀!