如何创建一个文本文件,它是一个数字,先于这个数字的词对?

问题描述 投票:0回答:3

我工作的一个新的项目和团队我被分配到的所有的Python。我不是在Python是精通,所以我想我会转向StackOverflow上寻求帮助。我的项目的一部分是写一个程序,读取文本文件,并从中发现是一个数字,并且先于数字在文件中的一切创造对。我做的唯一的事情就是让程序读取文本文件和打印整个事情。但我不知道如何得到它吐回对,是一个数字,它前面的字。任何帮助表示赞赏!谢谢。

文本文件的内容例如:

I have 3 apples.
The apples were very good.
I ate 7 bananas.
The bananas were just as good.

所需的输出:

have, 3
ate, 7

到目前为止我的代码:

in_file = open("FILE.txt", "rt")  
contents = in_file.read()       
in_file.close()                  
print(contents)

(逻辑发送回对,是一个数字,它前面的WORD)

python python-3.x file text
3个回答
1
投票

您应该使用正则表达式:

import re

with open('FILE.txt', 'r') as in_file:
    contents = in_file.read()

pairs = re.findall(r'(\w+)\s+(\d+)', contents)
print(pairs)

输出:

[('have', '3'), ('ate', '7')]

演示的模式:https://regex101.com/r/bZzlJs/1

如果你想要一个int,而不是为数字的字符串,你可以做

pairs = [(word, int(num)) for word, num in re.findall(r'(\w+)\s+(\d+)', contents)]

0
投票

尝试是这样的:

result = []
def is_num(text):
    try:
        float(text)
        return True
    except:
        return False
with open('myfile', 'rw') as nf:
    lines = nf.readlines()
    for line in lines:
        line_list = line.split()
        for idx, item in enumerate(line_list):
            if is_num(item):
                result.append([item, line_list[idx-1])

0
投票

所以,我把阅读所有的线作为一个字符串的文件。用空格代替“\ n”,那么我可以在每个空间通过拆分其分解成每个单词。然后通过分割词的任何时间迭代是正整数余打印及其前身字。 (我处理整数在行的开头,但没有文件的开头)

with open("FILE.txt","r") as f:    
    s = f.read()
    s = s.replace("\n"," ")
    s = s.split(" ")
    for k in range(s.length()):
        if(s[k].isdigit()):
            print(s[k-1],s[k])

注:ISDIGIT只能是数字是积极的,没有小数存在使用除了处理小数尝试

© www.soinside.com 2019 - 2024. All rights reserved.