如何获得'字符串'(?)和打印量

时间:2017-05-14 15:26:04

标签: python

我有一个在.txt中用':'分隔的不同单词的列表,如下:

banana:pinapple
apple:grapes
orange:nuts
...

如何获得分号左侧有单词的行数并打印该数字?

我用这个来分开它们:

string1, string2 = line.split(':')

我想打印这样的数字:

print(number of lines where there exists is a string1)

4 个答案:

答案 0 :(得分:0)

count = 0
for line in f:
    string1, string2 = line.split(':')
    if string1:
        count += 1
print(count)

您的问题询问左侧的单词数,这正是重要的。这将处理行:foo的情况。尽管如此,你还没有建议有没有冒号的行或有多行的行。此外,您还没有说左边会有多个单词。我选择忽略这些案例,因为你还没有表明它们的存在。

答案 1 :(得分:0)

fileName = 'myfile.txt'

counterDict = {}

with open(fileName,'r') as fh:
  for line in fh:
    left,right = line.rstrip('\n').split(':')
    counterDict[left] = counterDict.get(left,0)+1  

print(counterDict)

#cat myfile.txt

banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts

#结果

{'banana':3,'apple':3,'orange':3}

答案 2 :(得分:0)

因此,根据提供的所有答案,我不确定我是否理解您的问题。你想知道的是如何计算文本文件中的行数?

是的,我看到你说过#34;在结肠的左边有一个单词",但为什么你的一行上有一个冒号而没有任何其他文字?你的说法是你的程序以这样的方式编写文本"例如":"例如"对?

如果是这样的话,你就不会在一行中有一个冒号而没有任何其他文本,除非你故意输入任何仍然是什么东西。

def user_review(data_to_review):
    """ Present web form to user and receive their input """

    returnstruct = {}
    app = Flask(__name__)

    @app.route('/', methods=['GET'])
    def show_review_form():
        form = create_review_form(data_to_review)
        return render_template('reviewtemplate.tpl', form=form)

    # TODO - I currently split the handling into a different route because
    # when using the same route previously Safari would warn of resubmitting data.
    # This has the slightly unfortunate effect of creating multiple tabs.

    @app.route('/process_compare', methods=['POST'])
    def process_review_form():
        # this form object will be populated with the submitted information
        form = create_review_form(request.form, matchrecord=matchrecord)

        # handle submitted updates however necessary 
        returnstruct['matched'] = form.process_changes.data

        shutdown_flask_server()
        return "Changes submitted, you can close this tab"

    webbrowser.open('http://localhost:5000/', autoraise=True)
    app.run(debug=True, use_reloader=False)

    # The following will execute after the app is shutdown.
    print('Finished manual review, returning {}'.format(returnstruct))
    return(returnstruct)

def shutdown_flask_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

这有一些基本的错误检查形式,这里有一个没有它。

def get_total_lines(self, path):
    counter = 0
    try:
        if os.path.isfile(path):
            with open(path, 'r') as inFile:
                for i in enumerate(inFile):
                    counter = counter + 1
                    return str(counter)
        elif not os.path.isfile(path):
            print("Error: The file you're attempting to read does not exist, aborting reading process...")
    except IOError as exception:
        raise IOError('%s: %s' % (path, exception.strerror))
        return None

这将计算行数,如果你想剥离一个单词或冒号,它可以很容易地适应这一点。

答案 3 :(得分:-1)

获得行数而不是这样:

with open(listname) as list:
    lines = len(list.readlines())