【问题标题】:How to skip "Names" when reading text from a file?从文件中读取文本时如何跳过“名称”?
【发布时间】:2015-01-27 10:52:56
【问题描述】:

我正在编写一个程序,我应该在其中读取文件,跳过所有人员姓名并处理其他信息。

我应该使用什么逻辑来跳过阅读名称。

我从文件中读取单词,然后使用它们的出现频率制作词云。 对于像文章这样的琐碎事情,我做了一个列表,并确保如果阅读的单词在这篇文章列表中,它们不会被计算在内。(我是用字典做的)

但是我无法理解如何跳过阅读名称。

WordList=[]

with open('file.txt','r') as f:
    for line in f:
        for word in line.split():
            if len(word)>3:
                if word not in IgList:
                    WordList.append(word.lower())


# Get a set of unique words from the list

word_set =[]


for word in WordList[::-1]:
    if word not in word_set:
        word_set.append(word)


# create your frequency dictionary
freq = {}
# iterate through them, once per unique word.
for word in word_set:
    freq[word] = WordList.count(word) / float(len(WordList))

size=[]##Size of each word is stored here
for i in word_set:
    size.append(100*freq[i])

for i in range(0,len(word_set)):
    print size[i],word_set[i]

【问题讨论】:

  • 您介意分享您目前的工作吗?
  • 你在处理什么样的信息?
  • 我正在使用 python 通过 pygame 库创建一个词云。
  • 我假设您的意思是您正在计算文本中单词的频率,但要忽略名称 - 如果是这样,我建议检查每个单词是否在字典中并忽略不在字典中的单词。跨度>
  • 是的,我已经这样做了。检查上面,但是如何跳过“名称”,专有名词。

标签: python file python-2.7 input


【解决方案1】:

假设句子通常以冠词开头,“姓名”以大写字母

开头
IgList=list of articles 


with open('file.txt','r') as f:
    for line in f:
        for word in line.split():
                if word not in IgList:
                    if word[0] not in word.upper():##Cheking if first letter is Capital
                        WordList.append(word.lower())

如果单词以大写字母开头,则跳过。 可以编写额外的代码来跳过第一个读取的字。

【讨论】:

    【解决方案2】:
    with open("filename") as f:
        rd=f.readlines()
        print (rd[:x])
    

    xnames 之后的索引号,假设您知道文件中的名称在哪里。基本上它会跳过名称。例如,如果您的文件是这样的;

    John 25 USA
    Mary 26 Bangladesh
    Usain 63 Republic of the Congo
    

    你必须写;

    print (rd[1:])
    

    或者如果是这样的话;

    63 Republic of the Congo Usain
    26 Bangladesh Mary
    25 USA John
    

    你必须输入;

    print (rd[:1])
    

    【讨论】:

    • 我不知道名词的位置,文件是随机的。
    • 你的意思是“随机”?
    • 任何文本文件都可以作为输入,名称可以在这些文件中的任何位置。
    • 你应该做一个人工智能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多