帮助倒置字典 [英] Help with inverted dictionary
本文介绍了帮助倒置字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Python的新手,我正在努力。我有一个文本文件(* .txt)和
几千个条目,每个条目都在自己的行上(类似于手机
书)。我如何创建一个脚本来创建类似于反转的字母,这将允许我调用robert字典。并创建一个新文本
包含robert的所有行的文件?
非常感谢。
I''m new to Python and I''m struggling. I have a text file (*.txt) with
a couple thousand entries, each on their own line (similar to a phone
book). How do I make a script to create something like an inverted
dictionary that will allow me to call "robert" and create a new text
file of all of the lines that contain "robert"?
Thanks so much.
推荐答案
你好,
首先我不太清楚你的问题,但你可以做以下
步骤:
1.将文件转换为列表(list1)
2.使用正则表达式捕获list1的每个成员中的''robert''并添加到
list2
3.将list2转换为文件
pujo
Hello,
First I''m not so clear about your problem, but you can do the following
steps:
1. Transform your file into list (list1)
2. Use regex to capture ''robert'' in every member of list1 and add to
list2
3. Transform your list2 into a file
pujo
import re
name =" Robert"
f = file(''phonebook.txt'',''r'')
lines = [line.rstrip(" \ n")for f.readlines()]中的行
pat = re.compile(name,re.I)
related_lines = [行中行的行如果pat.search(行)]
然后你将related_lines中的行写入文件。我不是真的好吗?b $ b把文字写到文件上很多,嗯,是的。
import re
name = "Robert"
f = file(''phonebook.txt'',''r'')
lines = [line.rstrip("\n") for line in f.readlines()]
pat = re.compile(name, re.I)
related_lines = [line for line in lines if pat.search(line)]
And then you write the lines in related_lines to a file. I don''t really
write text to files much so, um, yeah.
好的,所以我的问题是我有一个包含所有这些实例的文本文件,
例如关于动物的5000个事实。我需要浏览文件
并将包含单词lion的所有事实(行)放入一个名为lion.txt的
文件中。如果我遇到一个尚未存在
文件的动物或其他单词,我需要为该单词创建一个文件并将该单词的所有实例放入
那个文件。我意识到这应该可以创建30,000个左右的文件。任何帮助都将非常值得赞赏。谢谢。 Reece
OK, so my problem is I have a text file with all of these instances,
for example 5000 facts about animals. I need to go through the file
and put all of the facts (lines) that contain the word lion into a file
called lion.txt. If I come across an animal or other word for which a
file does not yet exist I need to create a file for that word and put
all instances of that word into that file. I realize that this should
probably create 30,000 files or so. Any help would be REALLY
appreciated. Thanks. Reece
这篇关于帮助倒置字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文